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.
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)
Help removing 'null' from json output
Inconsistent JSON serialization of None keys ("None" instead of "null")
Working around JSON null values in Python - Stack Overflow
Dealing with json null in python - Stack Overflow
Videos
I'm writing a program that pulls its data from excel, and then outputs a long block of json code. However, occasionally the cells will be empty, and so the json code displays null. How can I remove the null outputs from my json so that it only displays the cells that currently have a value?
If you're using Python 2.6 or later, you can use the built-in json module:
>>> import json
>>> json.dumps([1, 2, 3, None, 4])
'[1, 2, 3, null, 4]'
See http://docs.python.org/library/json.html
When I tried the accepted solution json.dumps() returned NaN values rather than the null JavaScript is looking for. Therefore I found another solution that does not use json or simplejson packages. The following solution uses type checking of None in Django. The solution that inspired me can be found here.
I used it in my code as follows to populate a Javascript array correctly:
[
{% for val in data %}
{% if val is none %}
null,
{% else %}
{{ val }},
{% endif %}
{% endfor %}
],
The none object in Django will check the None value offered by python. It doesn't seem to correctly handle np.NaN objects though.