【问题标题】:How to merge 2 json files with a common key如何使用公共密钥合并 2 个 json 文件
【发布时间】: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
  • 那条评论无济于事,原因不同
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python json merge


【解决方案1】:

那是因为你正在更新根 json 对象并得到一个

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

而您想要的是从单个“值”更新单个“测试”并得到只是

{
    "tests": [...]
}

结果。

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

【讨论】:

  • 是的,而且是嵌套在 tests.json 文件中的“值”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
  • 1970-01-01
  • 2014-12-03
  • 2013-01-19
  • 2020-07-05
  • 2021-02-17
  • 2015-11-18
相关资源
最近更新 更多