合并重复键下存在的 json 对象

问题描述 投票:0回答:1

我有一个像这样的json文件:

{
    "parent1": {
        "child1": "bob"
    },
    "parent1": {
        "child2": "tom"
    },
    "parent2": {
        "child1": "jon"
    }
}

我想合并重复顶级键下存在的值。所以预期的输出应该是:

{
    "parent1": {
        "child1": "bob",
        "child2": "tom"
    },
    "parent2": {
        "child1": "jon"
    }
}

目前我正在使用以下代码来检查重复键:

import json

def check_duplicates(pairs):
    d = {}
    for key, val in pairs:
        if key in d:
            raise ValueError(f"Duplicate key(s) found: {key}")
        else:
            d[key] = val
    return d

filename = "test.json"
with open(filename, "r") as f:
    try:
        data = json.load(f, object_pairs_hook=check_duplicates)
    except ValueError as err:
        print(f"{filename}: Failed to decode: {err}")

知道如何合并它们吗?

python json
1个回答
0
投票
  1. 修改发现重复键时合并子词典的功能。
  2. 将此功能用作
    object_pairs_hook
    中的
    json.load
    import json
    from collections import defaultdict
    
    def merge_duplicates(pairs):
        d = defaultdict(dict)
        for key, val in pairs:
            if key in d:
                d[key].update(val)
            else:
                d[key] = val
        return dict(d)
    
    filename = "test.json"
    with open(filename, "r") as f:
        data = json.load(f, object_pairs_hook=merge_duplicates)
    
    print(json.dumps(data, indent=4))
© www.soinside.com 2019 - 2024. All rights reserved.