How can JSON data with null value be converted to a dictionary

Python

Python Problem Overview


{
  "abc": null,
  "def": 9
}

I have JSON data which looks like this. If not for null (without quotes as a string), I could have used ast module's literal_eval to convert the above to a dictionary.

A dictionary in Python cannot have null as value but can have "null" as a value. How do I convert the above to a dictionary that Python recognizes?

Python Solutions


Solution 1 - Python

You should use the built-in json module, which was designed explicitly for this task:

>>> import json
>>> data = '''
... {
...   "abc": null,
...   "def": 9
... }
... '''
>>> json.loads(data)
{'def': 9, 'abc': None}
>>> type(json.loads(data))
<class 'dict'>
>>>

By the way, you should use this method even if your JSON data contains no null values. While it may work (sometimes), ast.literal_eval was designed to evaluate Python code that is represented as a string. It is simply the wrong tool to work with JSON data.

Solution 2 - Python

One solution is to use a variable that contains None.

import json
null = None
data = { "test": null }
json.dumps(data)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2921139View Question on Stackoverflow
Solution 1 - Pythonuser2555451View Answer on Stackoverflow
Solution 2 - PythonavimimounView Answer on Stackoverflow