使用 Python 的 JSON 数据中的空值,而不是无值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28843876/
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
Nulls, instead of Nones, in JSON Data with Python
提问by Daniel
I'm working with the following data:
我正在处理以下数据:
[{"title": null, "metric1": 361429, "metric2": 36,},{"title": null, "metric1": 253798, "metric2": 48}]
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:
当我尝试将此数据分配给 Python 中的变量时(目的是将其解析),我收到以下错误消息:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'null' is not defined
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?
从我的研究来看,似乎None
是 Python 的null
. 我想知道的是,是否可以使用 Python 将null
数据中的None
's更改为's ?
I've tried creating a string out of the data, assigning it to data
, and replacing the null
's that way:
我已经尝试从数据中创建一个字符串,将其分配给data
,并以null
这种方式替换's:
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}]'
and I can't figure out how to turn it from a string back into JSON.
我不知道如何将它从字符串转换回 JSON。
EDIT: I am copying and pasting this data into the Python interpreter from a separate source.
编辑:我正在将此数据从单独的源复制并粘贴到 Python 解释器中。
采纳答案by Oliver W.
Much simpler!
简单多了!
Just assign None
to null
before assigning that list to a variable:
刚分配None
来null
分配该列表的变量之前:
null = None
var = [{"title": null, "metric1": 361429, "metric2": 36,},{"title": null, "metric1": 253798, "metric2": 48}]
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
.
然后,您将不需要对字符串(并返回到带有 的 Python 对象json.loads
)进行相当不必要的转换,只需将 替换null
为None
。
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
).
但是,只有当您从某个来源复制粘贴该代码时,这才是真正必要的。否则,规范的答案是使用json.loads
(或json.load
)。
回答by levi
As is mentioned above, you don't need to replace "null"
for "None"
如上所述,您不需要替换"null"
为"None"
Just
只是
import json
parsed_data = json.loads(data)