首页 > 解决方案 > 在 Python 中合并 JSON,同时保留唯一的键并覆盖公共键

问题描述

我有两个 JSON,我需要一些方法来合并唯一值并用后面的值覆盖公共键。只要可以制作内容,排序并不重要。

JSON 1

{ "key": {"a": "1", "b": "2", "c": "3", "list": ["5", "6", "7"] } }

JSON 2

{ "key": {"b": "9", "list": ["8"] } }

结果 JSON

{ "key": {"a": "1", "b": "9", "c": "3", "list": ["5", "6", "7", "8"] } }

标签: python

解决方案


因为您似乎想要保留一些值并覆盖其他值,所以我匆忙拼凑了一个递归函数来做到这一点,除非有一些边缘情况。

def combine(dict1, dict2):
    """Updates dict1 to contain dict2"""
    for key in dict2:
        if key in dict1:
            if isinstance(dict1[key], list): # If value is a list, we want special logic
                if isinstance(dict2[key], list): # if the "input" is a list, just do list + list
                    dict1[key] = dict1[key] + dict2[key]
                else:
                    dict1[key].append(dict2[key])
            elif isinstance(dict1[key], dict): # calling itself recursively
                dict1[key] = combine(dict1[key], dict2[key])
            else: # Overwrites all other values
                dict1[key] = dict2[key]
        else: # Creates the values that doesn't exist.
            dict1[key] = dict2[key]
    return dict1

这是一团糟,几乎无法阅读。无论如何,这是一个演示:

import json
json1 = '{ "key": {"a": "1", "b": "2", "c": "3", "list": ["5", "6", "7"] } }'
json2 = '{ "key": {"b": "9", "list": ["8"] } }'

json1 = json.loads(json1)
json2 = json.loads(json2)

print(json1) # {'key': {'a': '1', 'b': '2', 'c': '3', 'list': ['5', '6', '7']}}
print(json2) # {'key': {'b': '9', 'list': ['8']}}
print(combine(json1,json2)) # {'key': {'a': '1', 'b': '9', 'c': '3', 'list': ['5', '6', '7', '8']}}

推荐阅读