python - 在 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"] } }
解决方案
因为您似乎想要保留一些值并覆盖其他值,所以我匆忙拼凑了一个递归函数来做到这一点,除非有一些边缘情况。
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']}}
推荐阅读
- django - 使用 Google Cloud Platform 的标准环境时,我应该使用 gunicorn 为 Django 服务吗?
- mysql - zepplin mysql 解释器错误,无法获取 mysql:mysql-connector-java:5.1.38 的依赖项
- python - 在 Mac(终端)/Windows(命令行)中自动执行 Python 脚本
- angular - 从 Angular 中的模板引用变量中获取 ElementRef
- java - 单击表格 API 中的链接后,localhost 拒绝连接
- ios - 在 Flutter 插件上调用无法识别的选择器
- reactjs - 本地护照的已验证请求待处理
- javascript - 重新加载后隐藏按钮重新出现
- jquery - Node.js:会议未定义
- ruby-on-rails - 无法在日志查看器中查看日志