如何将具有空值的JSON数据转换为字典

问题描述:

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

我有如下所示的JSON数据.如果不是null(不带引号的字符串),则可以使用ast模块的literal_eval将上述内容转换为字典.

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.

Python中的字典不能将null作为值,但是可以将"null"作为值.如何将以上内容转换为Python可以识别的字典?

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?

您应使用内置的

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'>
>>>

顺便说一句,即使您的JSON数据不包含null值,您也应该使用此方法.尽管可能可行(有时),但ast.literal_eval旨在评估以字符串表示的 Python 代码.这只是使用JSON数据的错误工具.

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.