'Removing key from json file in Python (getting TypeError)

I have a this json file:

{
 "DailyForecasts": [
  {
   "Temperature": {
    "Minimum": {
     "Value": 2.9
    },
    "Maximum": {
     "Value": 16.1
    }
  },
 "HoursOfSun": 12,
 "AirAndPollen": [
    {
      "Name": "AirQuality",
      "Value": 37,
      "CategoryValue": 1
    },
    {
      "Name": "UVIndex",
      "Value": 5,
      "CategoryValue": 2
    }
   ]
  }
 ]
}

I would like to remove "CategoryValue" key from "AirAndPollen" array. I tried this Python code, but getting:

TypeError: list indices must be integers or slices, not str

My Python code:

import json

with open('accu-test.json') as f:
    data = json.load(f)

for remove in data['DailyForecasts']:
    del remove['AirAndPollen']['CategoryValue']

print(json.dumps(data, indent=2))

What's the recommended approach in this case? Thank you.



Solution 1:[1]

If you add a statement print(remove['AirAndPollen']) you'll see that remove['AirAndPollen'] is not a single object but rather a list. You need an additional loop to operate on each on of those objects in turn.

Solution 2:[2]

try this one:

data = {
    "DailyForecasts": [
        {
            "Temperature": {
                "Minimum": {
                    "Value": 2.9
                },
                "Maximum": {
                    "Value": 16.1
                }
            },
            "HoursOfSun": 12,
            "AirAndPollen": [
                {
                    "Name": "AirQuality",
                    "Value": 37,
                    "CategoryValue": 1
                },
                {
                    "Name": "UVIndex",
                    "Value": 5,
                    "CategoryValue": 2
                }
            ]
        }
    ]
}

air_and_pollen = data.get("DailyForecasts")[0]["AirAndPollen"]
for i in air_and_pollen:
    i.pop("CategoryValue")
data.get("DailyForecasts")[0]["AirAndPollen"] = air_and_pollen
print(data)

Solution 3:[3]

You could use nested_delete from the nested_lookup module:

NB: I wrapped the json data into a content variable:

from nested_lookup import nested_delete

#specify the key u wish to remove
content = nested_delete(content,'CategoryValue')

print(content)

{'DailyForecasts': [{'Temperature': {'Minimum': {'Value': 2.9},
    'Maximum': {'Value': 16.1}},
   'HoursOfSun': 12,
   'AirAndPollen': [{'Name': 'AirQuality', 'Value': 37},
    {'Name': 'UVIndex', 'Value': 5}]}]}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Larry Lustig
Solution 2 Gabio
Solution 3 halfer