'Python - remove json object if missing key

I'm looking to delete all objects from some JSON data if it is missing the key or value.

Here is a snippet of the JSON data:

[
  {
    "cacheId": "eO8MDieauGIJ",
    "pagemap": {}
  },
  {
    "cacheId": "AWYYu9XQnuwJ",
    "pagemap": {
      "cse_image": [
        {
          "src": "https://someimage.png"
        }
       ]
      }
   },
  {
    "cacheId": "AWYYu9XQnuwJ",
    "pagemap": {
      "cse_image": [
        {
        }
       ]
      }
   }
]

I'm looking to delete the 1st and 3rd object in the data because the 1st object has an empty ['pagemap'] and the 3rd object has an empty ['pagemap']['cse_image']

Here is what I've tried so far without any luck:

for result in data[:]:
    if result['pagemap']['cse_image'] == []:
        data.remove(result)

for result in data[:]:
    if result['pagemap'] == None:
        data.remove(result)

for result in data[:]:
    if len(result['pagemap']) == 0:
        data.remove(result)

Thanks for the help!



Solution 1:[1]

If that data structure remains consistent, you can do it with a list comprehension.

[e for e in d if e["pagemap"] and e["pagemap"]["cse_image"] and any(e["pagemap"]["cse_image"])]

produces:

[{'cacheId': 'AWYYu9XQnuwJ', 'pagemap': {'cse_image': [{'src': 'https://someimage.png'}]}}]

Where d is your given data structure.

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 Keith