Using Python, I need to delete all objects in JSON array that have specific value of 'name' key. However, I can't do that from a loop.
Imaging I want to delete all items having 'bad' as name in the following input:
{
'myArray' : [
{
'name' : 'good',
'value' : '1'
},
{
'name' : 'bad',
'value' : '2'
}
]
}
So I use the following Python test case:
myData = {'myArray': [{'name': 'good', 'value': '1'}, {'name': 'bad', 'value': '2'}]}
for a in myData['myArray']:
if (a['name'] =='bad'):
del a
print(json.dumps(myData))
And I see that the myData is not changed.
I assume this is because I try to delete an iterator of a loop, that might be considered as risky action by interpreter, however no runtime error or warning is reported by Python.
What's the recommended approach in this case?
Thanks!
One of approaches from Remove element from list when using enumerate() in python - a loop over a copy of the list referred as [:] - works too:
for a in myData['myArray'][:]:
if (a['name'] == u'bad'):
myData['myArray'].remove(a)
Thanks everyone!
Use a (nested) dict/list comprehension. Never try to delete elements of an object while iterating over it
>>> [x for x in myData['myArray'] if x['name'] != 'bad']
[{'name': 'good', 'value': '1'}]
Assign the result to myData['myArray']
, or whatever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With