Skip to main content
 首页 » 编程设计

Python-如何在类似字典的 json 字符串中检索与同一键关联的多个值

2025年05月04日22虾米姐

好的,所以我有来自网页的 json 源代码,在此源代码中,同一个词(“作者”)用作多个值的键。如何检索“作者”的所有值?

例如

"author": "SampleMan", "author":"NonSampleMan", "author":"BoringMan" 

如何让 Python 返回 ["SampleMan", "NonSampleMan", "BoringMan"]?

请您参考如下方法:

您可以将 object_pairs_hook 传递给 json.loads这将收集具有相同键值的列表:

from collections import defaultdict 
import json 
 
s = '{"author": "SampleMan", "author":"NonSampleMan", "author":"BoringMan", "foo":"bar", "bar": [1]}' 
 
def hook(pairs): 
    d = defaultdict(list) 
    for k, v in pairs: 
        d[k].append(v) 
 
    return {k: v if len(v) > 1 else v[0] for k, v in d.items()} 
 
print(json.loads(s, object_pairs_hook=hook)) 

输出:

{'bar': [1], 'author': ['SampleMan', 'NonSampleMan', 'BoringMan'], 'foo': 'bar'} 

在上面的钩子(Hook)中接收 list 的 (key, value) 元组存储到 defaultdict其中值是列表。一旦对元组进行迭代,它将生成结果 dict,如果有多个具有给定键的项目,则值为列表。

Python 文档对钩子(Hook)的描述如下:

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict() will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.