59
{
  "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?

Braiam
  • 1
  • 11
  • 47
  • 78
user2921139
  • 1,669
  • 4
  • 17
  • 25

2 Answers2

85

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.

  • hd1 - for some reason. iCodez comment showed up first. Sorry! so i had to mark it as the answer but thanks Good show! – user2921139 Nov 26 '14 at 02:11
  • 1
    @user2921139: If you really want to translate `null` to `"null"` rather than `None` as your question implies, you will need to do a bit of extra work. But I suspect that you don't want that. – abarnert Nov 26 '14 at 02:34
  • No abarnert. I am good but curious - how would u do the null to "null"? – user2921139 Nov 26 '14 at 04:40
  • Is there any way to do null to "null" ? – Rachel Dec 28 '18 at 11:01
  • To replace you can surely use the string.replace() method, see https://stackoverflow.com/a/9452122/11120444 – avimimoun Feb 01 '21 at 10:04
31

One solution is to use a variable that contains None.

import json
null = None
data = { "test": null }
json.dumps(data)
avimimoun
  • 799
  • 9
  • 23