Python + JSON, what happened to None?


Dumping and loading a dict with None as key, results in a dictionary with 'null' as the key.

将None作为键转储并加载dict,会产生一个以'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 dict with None keys?

我在这做错了什么?为什么我不能用None键序列化/反序列化dict?

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'}

3 个解决方案

#1


18  

JSON objects are maps of strings to 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}

#2


10  

According to the specification, None is 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模块应该在序列化时引发异常,而不是静默生成值的字符串表示。

EDIT Just 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规范,我仍然觉得它有问题)。

#3


-1  

As @dan04 shows, None is converted to 'null'.
Everything is fine, the value is stored into the dict with "null: 'What happened to None?'"

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

正如@ dan04所示,None转换为'null'。一切都很好,价值存储在dict中,“null:'没有发生什么?'”但随后出现了另一个带有'null'的Key。所以带有None /'null'-Key的旧值(“没有发生什么?”)被“繁荣”所覆盖。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号