繁体   English   中英

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

[英]How to merge 2 json files with common key

我想合并 2 个 JSON 文件

file1.json 看起来像空

{
  "tests": [{
    "id": 2,
    "title": "Smoke test",
    "value": "",
    "additional_info": "info..."
  }, {
    "id": 41,
    "title": "Debug test",
    "value": "",
    "additional_info": "info..."
  }, {...

file2.json 具有该

{
  "values": [{
    "id": 2,
    "value": "passed"
  }, {
    "id": 41,
    "value": "passed"
  }, {...

我正在尝试这段代码

import json

with open("file1.json") as fo:
    data1 = json.load(fo)

with open("file2.json") as fo:
    data2 = json.load(fo)

data1.update(data2)

with open("report.json", "w") as fo:
    json.dump(data1, fo)

但它只是连接来自 file1.json 和 file2.json 的 output

最终结果。json 应该是这样的:

{
  "tests": [{
    "id": 2,
    "title": "Smoke test",
    "value": "passed",
    "additional_info": "info..."
  }, {
    "id": 41,
    "title": "Debug test",
    "value": "passed",
    "additional_info": "info..."
  }, {...

那是因为您正在更新根 json object 并获得

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

虽然您想要的是从单个“值”更新单个“测试”并获得公正

{
    "tests": [...]
}

因此。

尝试遍历两个 json 中的每个 object。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM