【发布时间】:2022-01-22 06:31:16
【问题描述】:
我想合并 2 个 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 与 value
{
"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,只能创建另一个文件来保存所有更改。
【问题讨论】:
-
这能回答你的问题吗? Merge JSON data with Python
-
那条评论无济于事,原因不同
-
请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。