如何将具有空值的JSON数据转换为字典 [英] How can JSON data with null value be converted to a dictionary

查看:462
本文介绍了如何将具有空值的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.

这篇关于如何将具有空值的JSON数据转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆