使用Python在JSON数据中使用Null(而不是None) [英] Nulls, instead of Nones, in JSON Data with Python

查看:6143
本文介绍了使用Python在JSON数据中使用Null(而不是None)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理以下数据:

[{"title": null, "metric1": 361429, "metric2": 36,},{"title": null, "metric1": 253798, "metric2": 48}]

当我尝试将此数据分配给Python中的一个变量(目的是解析它)时,我收到以下错误消息:

When I attempt to assign this data to a variable in Python (with the aim of parsing it out), I receive the following error message:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'null' is not defined

根据我的研究,看来None是Python的null.我想知道的是,是否可以使用Python将数据中的null更改为None?

From my research, it appears that the None is Python's null. What I'm wondering is, is it possible to change the null's in my data to None's using Python?

我试图从数据中创建一个字符串,将其分配给data,并以此方式替换null:

I've tried creating a string out of the data, assigning it to data, and replacing the null's that way:

data = data.replace('null','None')

但是会导致数据本身为字符串:

but that results in a string of the data itself:

data = '[{"title": None, "metric1": 361429, "metric2": 36,},{"title": None, "metric1": 253798, "metric2": 48}]'

而且我不知道如何将其从字符串转换回JSON.

and I can't figure out how to turn it from a string back into JSON.

我正在将这些数据从单独的源复制并粘贴到Python解释器中.

I am copying and pasting this data into the Python interpreter from a separate source.

推荐答案

简单得多!

在将列表分配给变量之前,只需将None分配给null:

Just assign None to null before assigning that list to a variable:

null = None
var = [{"title": null, "metric1": 361429, "metric2": 36,},{"title": null, "metric1": 253798, "metric2": 48}]

然后,您只需要将null替换为None,就不需要进行不必要的转换为字符串(并返回为json.loads的Python对象).

Then you won't need to do the rather unnecessary conversion to a string (and back to a Python object with json.loads) only to replace null by None.

但是,只有从某些源复制粘贴该代码时,这才是真正必要的.否则,规范的答案是使用json.loads(或json.load).

But that is only really necessary if you're copy-pasting that code from some source. Otherwise, the canonical answer is to use json.loads (or json.load).

这篇关于使用Python在JSON数据中使用Null(而不是None)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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