Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

People also ask

How do I convert a JSON to a dictionary?

To convert json to dict in Python, use the json. load() function. The json. load() is a built-in function that deserializes json data to a Python object.

Can JSON have null values?

It can also be a list or a bare value (i.e. string, number, boolean or null). If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null . No braces, no brackets, no quotes.


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.


One solution is to use a variable that contains None.

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