gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:08:57 34 4
gpt4 key购买 nike

>>> 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com