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!
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')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.