Python json模块生成非唯一键 [英] Python json module generates non-unique keys

查看:111
本文介绍了Python json模块生成非唯一键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

According to JSON specification https://tools.ietf.org/html/rfc8259 object's keys should be unique

  1. 对象

  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对象

But it's possible to create json object with two same keys

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规范,则对象(如字典)为:

In the JSON spec, the object (like a dict) is:

对象结构表示为一对大括号 周围零个或多个名称/值对(或成员). 名称是 字符串.

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对于输入对象非常宽容.它将隐式将整数键转换为字符串,这可能会导致数据丢失/键冲突,就像您在此处看到的那样.它还会破坏往返loads(dumps(d)).

Emphasis mine. Python's json.dumps is very forgiving with the input object. It will implicitly convert integer keys to strings, and this can result in data loss / key collisions just as you've seen here. It also breaks the round trip loads(dumps(d)).

如果您担心上下文中的数据丢失,请考虑使用更严格的json库,例如

If the data loss is a concern in your context, consider to use a stricter json library, e.g.

>>> 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中进行更改的机会大约为零.

In my opinion, yes. I've seen a lot of bugs caused by this, and would prefer if the stdlib json.dumps was strict by default, with an opt-in keyword argument for enabling any implicit conversions. However, the chances of this getting changed in Python are approximately zero.

这篇关于Python json模块生成非唯一键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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