python - json.loads 允许字典中的重复键,覆盖第一个值

标签 python json

>>> raw_post_data = request.raw_post_data
>>> print raw_post_data
{"group":{"groupId":"2", "groupName":"GroupName"}, "members":{"1":{"firstName":"fName","lastName":"LName","address":"address"},"1": {"firstName":"f_Name","lastName":"L_Name","address":"_address"}}}
>>> create_request = json.loads(raw_post_data)
>>> print create_request
{u'group': {u'groupName': u'GroupName', u'groupId': u'2'}, u'members': {u'1': {u'lastName': u'L_Name', u'firstName': u'f_Name', u'address': u'_address'}}}

正如你所见,当我使用 json.dumps()

时,键为“1”的成员被覆盖

有什么方法可以在 python 中将其捕获为异常,说在来自客户端的请求中发现重复键?

最佳答案

The rfc 4627 for application/json media type推荐唯一键,但没有明确禁止它们:

The names within an object SHOULD be unique.

来自 rfc 2119 :

SHOULD This word, or the adjective "RECOMMENDED", mean that there
may exist valid reasons in particular circumstances to ignore a
particular item, but the full implications must be understood and
carefully weighed before choosing a different course.

import json

def dict_raise_on_duplicates(ordered_pairs):
    """Reject duplicate keys."""
    d = {}
    for k, v in ordered_pairs:
        if k in d:
           raise ValueError("duplicate key: %r" % (k,))
        else:
           d[k] = v
    return d

json.loads(raw_post_data, object_pairs_hook=dict_raise_on_duplicates)
# -> ValueError: duplicate key: u'1'

关于python - json.loads 允许字典中的重复键,覆盖第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14902299/

相关文章:

jquery - jQuery 是否有内置的 JSON 支持?

java - 如何在 Jackson json 库中执行 peek()?

python - 增加 Pytorch 神经网络数据集的批量大小

python - 在 Python 中,如何使用不使用 YAML 标记的数据绑定(bind)来解析 YAML?

python - 如何使用 tkinter 显示函数调用的输出?

json - Spring Boot json 在没有默认构造函数的情况下建模

javascript - 如何用 Javascript 捕获来自另一个网站的脚本的响应(它返回纯文本)?

python - Django 说该表不存在

python - python中负稀疏矩阵的sqrt

javascript - jQuery ajax 返回readyState 1或不正确的数据类型