Skip to content
Advertisement

Filter null values from JSON

I receive the following JSON from the MS Graph API:

[
  {
    "audio": null,
    "package": null,
    "pendingOperations": null,
    "photo": null,
    ....
    "webUrl": null,
    "createdByUser": null,
    "lastModifiedByUser": null,
    "id": "0145415166458484754....",
    "@odata.type": "#microsoft.graph.driveItem"
  }
]

How can I filter the null values using Python (3.9) ?

Advertisement

Answer

First of all, processing it is easier when it’s been converted to python data structure, such as a dict. The built-in json module can convert a json-string into python objects using json.loads.

import json
data = json.loads(my_json_string)

You can create a new dictionary without the None-values by iterating over the items. Python uses None in place of null, so we have to filter on that

filtered_data = {}
for key, value in data.items():
    if value != None:
        filtered_data[key] = value

Or more compactly:

filtered_data = {k:v for k, v in data.items() if v != None}

Your example data is a list of dictionaries, so you’ll have to this to each element in the list.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement