Python json模块生成非唯一键

根据
JSON规范
https://tools.ietf.org/html/rfc8259,对象的键应该是唯一的

  1. Objects

    An object structure is represented as a pair of curly brackets
    surrounding zero or more name/value pairs (or members). A name is a
    string. A single colon comes after each name, separating the name
    from the value. A single comma separates a value from a following
    name. The names within an object SHOULD be unique.

但是可以用两个相同的键创建json对象

Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
>>> import json
>>> json.dumps({1: 'value1', "1": 'value2'})
'{"1": "value1", "1": "value2"}'

这是一个错误吗?

最佳答案 在
JSON spec中,对象(如dict)是:

An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members). A name is a
string.

强调我的. Python的json.dumps对输入对象非常宽容.它将隐式地将整数键转换为字符串,这可能导致数据丢失/键冲突,就像您在此处看到的那样.它还打破往返载荷(转储(d)).

如果数据丢失是您的上下文中的一个问题,请考虑使用更严格的json库,例如

>>> import demjson  # pip install demjson
>>> demjson.encode({1: 'value1', "1": 'value2'}, strict=True)
# JSONEncodeError: ('object properties (dictionary keys) must be strings in strict JSON', 1)

Is it error?

在我看来,是的.我已经看到了很多由此引起的错误,并且如果默认情况下stdlib json.dumps是严格的,并且使用opt-in关键字参数来启用任何隐式转换,我更愿意.但是,在Python中改变这种情况的几率几乎为零.

点赞