Reputation: 355
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!
Upvotes: 6
Views: 13146
Reputation: 355
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!
Upvotes: 4
Reputation: 33970
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.
Upvotes: 1
Reputation: 383
myData = {'myArray': [{'name': 'good', 'value': '1'}, {'name': 'bad', 'value': '2'}]}
myData_clean = [x for x in myData['myArray'] if x['name'] !='bad']
myData_clean = {'myArray':myData_clean}
print(myData_clean)
output:
{'myArray': [{'name': 'good', 'value': '1'}]}
Upvotes: 0
Reputation: 98
You can use the list comprehension. Below is the reference.
new_list = [obj for obj in myData['myArray'] if(obj['name'] != 'bad')]
print new_list
Upvotes: 0