Python + JSON,None 怎么了?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3548635/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:40:37  来源:igfitidea点击:

Python + JSON, what happened to None?

pythonjsondictionary

提问by safl

Dumping and loading a dict with Noneas key, results in a dictionarywith 'null'as the key.

倾销与加载字典None的关键,结果字典'null'作为重点。

Values are un-affected, but things get even worse if a string-key 'null'actually exists.

值不受影响,但如果字符串键'null'实际存在,情况会更糟。

What am I doing wrong here? Why can't I serialize/deserialize a dictwith Nonekeys?

我在这里做错了什么?为什么我不能dictNone键序列化/反序列化 a ?

Example

例子

>>> json.loads(json.dumps({'123':None, None:'What happened to None?'}))
{u'123': None, u'null': u'What happened to None?'}
>>> json.loads(json.dumps({'123':None, None:'What happened to None?', 'null': 'boom'}))
{u'123': None, u'null': u'boom'}

采纳答案by dan04

JSON objects are maps of stringsto values. If you try to use another type of key, they'll get converted to strings.

JSON 对象是字符串到值的映射。如果您尝试使用其他类型的键,它们将被转换为字符串。

>>> json.loads(json.dumps({123: None}))
{'123': None}
>>> json.loads(json.dumps({None: None}))
{'null': None}

回答by Dirk

According to the specification, Noneis not a valid key. It would amount to a JSON object expression, which looks like

根据规范,None不是有效的密钥。它相当于一个 JSON 对象表达式,看起来像

{ ..., null: ..., ... }

which is not valid (i.e., cannot be generated using the syntax diagram.)

这是无效的(即,不能使用语法图生成。)

Arguably, the JSON module should have raised an exception upon serialization instead of silently generating a string representation of the value.

可以说,JSON 模块应该在序列化时引发异常,而不是默默地生成值的字符串表示。

EDITJust saw, that the behaviour of the module is documented(somewhat implicitly):

编辑刚刚看到,模块的行为被记录在案(有点隐含):

If skipkeys is True (default: False), then dict keys that are not of a basic type (str, unicode, int, long, float, bool, None) will be skipped instead of raising a TypeError.

如果 skipkeys 为 True(默认值:False),则将跳过不是基本类型(str、unicode、int、long、float、bool、None)的 dict 键,而不是引发 TypeError。

so it seems, as if this behaviour is intentional (I still find it questionable given the current JSON specification).

所以看起来,好像这种行为是故意的(鉴于当前的 JSON 规范,我仍然觉得它有问题)。

回答by Duncan MC Leod

As @dan04 shows, Noneis converted to 'null'.

正如@dan04 所示,None转换为'null'.

Everything is fine, the value is stored into the dict with

一切都很好,值存储到字典中

"null": "What happened to None?"

But then came another Key called 'null'.

但随后又出现了另一个名为 的 Key 'null'

So the old value of the None/'null'-Key ("What happened to None?") is overwritten with "boom".

因此 None/ 'null'-Key ( "What happened to None?")的旧值被覆盖"boom"