如何将具有空值的JSON数据转换为字典 [英] How can JSON data with null value be converted to a dictionary
问题描述
{
"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.
这篇关于如何将具有空值的JSON数据转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!