如何用一个公共密钥合并2个json文件



我想合并两个JSON文件

tests.json具有空的,其中一些是嵌套的

{
"tests": [{
"id": 1,
"value": "",
"values": "info..."
}, {
"id": 41,
"title": "Debug test",
"value": "",
"values": [{
"id": 345,
"value": "",
"values": [ {
"id": 230,
"values": [{
"id": 234,
"value": ""
}, {
"id": 653,
"value": ""
}]
}]
}],
}, {...

values.json与

{
"values": [{
"id": 2,
"value": "passed"
}, {
"id": 41,
"value": "passed"
}, {
"id": 345,
"value": "passed"
}, {
"id": 230,
"value": "passed"
},{
"id": 234,
"value": "passed"
},{
"id": 653,
"value": "passed"
},{...

这个代码运行良好,但我需要使它更兼容

import json
with open("tests.json") as fo:
data1 = json.load(fo)
with open("values.json") as fo:
data2 = json.load(fo)
for dest in data1['tests']:
if 'values' in dest:
for dest_1 in dest['values']:
if 'values' in dest_1:
for dest_2 in dest_1['values']:
if 'values' in dest_2:
for dest_3 in dest_2['values']:
for source in data2['values']:
if source['id'] == dest_3['id']:
dest_3['value'] = source['value']
for source in data2['values']:
if source['id'] == dest_2['id']:
dest_2['value'] = source['value']
for source in data2['values']:
if source['id'] == dest_1['id']:
dest_1['value'] = source['value']
for source in data2['values']:
if source['id'] == dest['id']:
dest['value'] = source['value']
with open("report.json", "w") as write_file:
json.dump(data1, write_file, indent=2)

据我所知,我需要递归地检查file1.json在该块中是否有"values"参数和空的"value"参数。此外,我不能触摸源tests.json,只能创建另一个文件来保存所有更改。

这是因为您正在更新根json对象并获得

{
"tests": [...],
"values": [...]
}

而你想要的是更新个人";测试";从个人";值";只得到

{
"tests": [...]
}

结果。

尝试循环遍历两个json中的每个对象。

最新更新