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!
delona, which is the variable that the result of (implicitely) callingnexton the (invisible) iterator is assigned to. So you delete the variable, but then on the next iteration, that variable is simply re-created. You want to mutate your collection, but you probably shouldn't while iterating