python 的 json
模块在映射中有重复键时执行一些规范:
import json
>>> json.loads('{"a": "First", "a": "Second"}')
{u'a': u'Second'}
我知道此行为在 documentation 中指定:
The RFC specifies that the names within a JSON object should be unique, but does not specify how repeated names in JSON objects should be handled. By default, this module does not raise an exception; instead, it ignores all but the last name-value pair for a given name:
对于我当前的项目,我绝对需要确保文件中不存在重复键,如果是这种情况,我会收到错误/异常吗?如何实现?
我仍然停留在 Python 2.7 上,因此也适用于旧版本的解决方案对我帮助最大。
最佳答案
那么,您可以尝试使用 JSONDecoder
类并指定一个自定义 object_pairs_hook
,它将在重复数据删除之前接收它们。
import json
def dupe_checking_hook(pairs):
result = dict()
for key,val in pairs:
if key in result:
raise KeyError("Duplicate key specified: %s" % key)
result[key] = val
return result
decoder = json.JSONDecoder(object_pairs_hook=dupe_checking_hook)
# Raises a KeyError
some_json = decoder.decode('''{"a":"hi","a":"bye"}''')
# works
some_json = decoder.decode('''{"a":"hi","b":"bye"}''')
关于python - Python 中的 Json : Receive/Check duplicate key error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16172011/