I receive the following JSON from the MS Graph API:
JavaScript
x
15
15
1
[
2
{
3
"audio": null,
4
"package": null,
5
"pendingOperations": null,
6
"photo": null,
7
.
8
"webUrl": null,
9
"createdByUser": null,
10
"lastModifiedByUser": null,
11
"id": "0145415166458484754....",
12
"@odata.type": "#microsoft.graph.driveItem"
13
}
14
]
15
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.
JavaScript
1
3
1
import json
2
data = json.loads(my_json_string)
3
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
JavaScript
1
5
1
filtered_data = {}
2
for key, value in data.items():
3
if value != None:
4
filtered_data[key] = value
5
Or more compactly:
JavaScript
1
2
1
filtered_data = {k:v for k, v in data.items() if v != None}
2
Your example data is a list of dictionaries, so you’ll have to this to each element in the list.