【发布时间】:2014-11-26 01:55:57
【问题描述】:
{
"abc": null,
"def": 9
}
我有这样的 JSON 数据。如果不是 null(没有引号作为字符串),我可以使用 ast 模块的 literal_eval 将上述内容转换为字典。
Python 中的字典不能将 null 作为值,但可以将 "null" 作为值。如何将上述内容转换为 Python 识别的字典?
【问题讨论】:
标签: python
{
"abc": null,
"def": 9
}
我有这样的 JSON 数据。如果不是 null(没有引号作为字符串),我可以使用 ast 模块的 literal_eval 将上述内容转换为字典。
Python 中的字典不能将 null 作为值,但可以将 "null" 作为值。如何将上述内容转换为 Python 识别的字典?
【问题讨论】:
标签: python
您应该使用专门为此任务设计的内置json module:
>>> 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 数据的错误工具。
【讨论】:
null 翻译成"null" 而不是您的问题所暗示的None,则需要做一些额外的工作。但我怀疑你不想这样。
一种解决方案是使用包含 None 的变量。
import json
null = None
data = { "test": null }
json.dumps(data)
【讨论】: