Reputation: 881
Using Python3, I have a JSON output stored in a variable. The output contains something like this:
{
"department": "inventory",
"products": [
{
"color": "red",
"shape": "circle",
"size": "large"
},
{
"color": "blue",
"shape": "square",
"size": "small"
},
{
"color": "green",
"shape": "triangle",
"size": "medium"
}
}
I'm trying to remove any object, within the "products" array, that have a value for "size" as "large" or "medium", leaving with a new output of:
{
"department": "inventory",
"products": [
{
"color": "blue",
"shape": "square",
"size": "small"
},
}
I am somewhat successful using a combination of a for statement with an if statement outside of the array using pop, but I can't seem to figure out how to do it just for the objects within the products array.
I have tried the following:
for element in products
if last_login[i]["size"] == "medium":
del element
Which just gives me this:
KeyError: 0
Please feel free to ask more questions if needed,
Any help would be greatly appreciated!
Upvotes: 0
Views: 442
Reputation: 9061
Instead of deleting you can just filter and reassign
import json
d = json.loads(json_data)
d['products'] = [x for x in d['products'] if x['size'] not in ('large', 'medium')]
Upvotes: 4