SirLancillotto
SirLancillotto

Reputation: 49

Remove JSON element on loop in Python

I have this JSON

{"data": 
    [   
        {   
            "id": "11111", 
            "description": "Description 1", 
            "to_remove": "blah",
            "state": "Assigned"
        },
        {   
            "id": "2222", 
            "description": "Description 2",         
            "to_remove": "blah"
        },
        {   
            "id": "33333", 
            "description": "Description 3", 
            "to_remove": "blah",
            "state": "Assigned"
        }
]}

I need to remove all object where the "state" is not present and remove a single key (to_remove) in order to have this output:

{"data": 
    [   
        {   
            "id": "11111", 
            "description": "Description 1", 
            "state": "Assigned"
        },
        {   
            "id": "33333", 
            "description": "Description 3", 
            "state": "Assigned"
        }
]}

I tried with this code:

      json_data = json.loads(data)

      for element in json_data['data']:
          if 'state' in element:
             del element['to_remove']   
          else:
             del element

But the output is this:

{"data": 
    [   
        {   
            "id": "11111", 
            "description": "Description 1", 
            "state": "Assigned"
        },
        {   
            "id": "2222", 
            "description": "Description 2"          
            "to_remove": "blah",
        },
        {   
            "id": "33333", 
            "description": "Description 3", 
            "state": "Assigned"
        }
]}

I am able to remove a single key, but not all element. The del element command not return error. If I use a del element['to_remove'] after del element I have error "name element not exist"

Upvotes: 1

Views: 1380

Answers (1)

user2390182
user2390182

Reputation: 73450

del element just unbinds the loop variable element. That does not affect any other references to the same object. It does not remove it from the list. And if it did, you would be removing from a list while iterating it which is also bad.

Instead, rebuild the list along the following lines:

data = []
for element in json_data['data']:
    if 'state' in element:
        del element['to_remove']   
        # more robust: element.pop('to_remove', None)
        data.append(element)
json_data['data'] = data

Upvotes: 3

Related Questions