Python 如何将具有空值的 JSON 数据转换为字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27140090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can JSON data with null value be converted to a dictionary
提问by user2921139
{
"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 astmodule's literal_evalto convert the above to a dictionary.
我有看起来像这样的 JSON 数据。如果不是 null (没有引号作为字符串),我可以使用ast模块literal_eval将上述内容转换为字典。
A dictionary in Python cannot have nullas value but can have "null"as a value. How do I convert the above to a dictionary that Python recognizes?
Python 中的字典不能具有null作为值,但可以具有"null"作为值。如何将上述内容转换为 Python 识别的字典?
采纳答案by user2921139
You should use the built-in jsonmodule, which was designed explicitly for this task:
您应该使用专门为此任务设计的内置json模块:
>>> 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 nullvalues. While it may work (sometimes), ast.literal_evalwas designed to evaluate Pythoncode that is represented as a string. It is simply the wrong tool to work with JSON data.
顺便说一句,即使您的 JSON 数据不包含任何null值,您也应该使用此方法。虽然它可能工作(有时),ast.literal_eval但旨在评估表示为字符串的Python代码。它只是处理 JSON 数据的错误工具。
回答by avimimoun
One solution is to use a variable that contains None.
一种解决方案是使用包含 None 的变量。
import json
null = None
data = { "test": null }
json.dumps(data)

