【问题标题】:Merge two json files in python在python中合并两个json文件
【发布时间】:2019-11-13 23:54:45
【问题描述】:

我有一个场景,我有两个 json 文件。假设 fileA.json 和 fileB.json 在两个文件中都有一些数据。在fileA中,我有一些数据,在fileB中,我需要在fileA中添加一些更改。所以在合并两个文件后,我希望它将数据保存在名为 fileC 的第三个文件中,具有相同的结构和更新的数据,但数据不应该丢失。

这是我的示例文件:-

文件A

{  
  "data1":[  
     {  
       "id":"1",
       "name":"abc"
     },
     {  
       "id":"2",
       "name":"xyz"
     }
  ],
 "data2":[  
     {  
       "id":"1",
       "data1_id":"2",
          "data3_ids":[  
              "1"
            ]
     },
     {  
       "id":"2",
       "user_id":"3",
          "data3_ids":[  
              "2"
            ]
     }
  ],
  "data3":[  
     {  
       "id":"1",
       "demo":"pqr",
       "title":"Never Be the Same"
     },
     {  
       "id":"2",
       "demo":"Zedd",
       "title":"The Middle"
     }
  ]
}

文件B

{  
  "data2":[  
    {  
       "id":"1",
       "data1_id":"2",
          "data3_ids":[  
               "1",
               "2"
           ]
    }
  ]
}

我想在 data2 存在的同一位置用 fileB 更新 fileA,但在 data2_ids 中更新值为“2”。

这是我尝试过的代码:-

import json

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

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

data1.update(data2)

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

这段代码我面临的问题是,虽然我正在获取 fileB 的数据,但丢失了 fileA 的数据。谁能给我一些解决方案。

【问题讨论】:

  • 请添加两个文件示例 json 数据。
  • update 只需替换新键的添加值或完全替换字典中现有键的值。如果您的 Json 比每个键的单个值更复杂,update 将不够。不幸的是,它取决于 json 结构,我们无法猜测......
  • 用示例文件更新了我的问题,还更新了我想要更新的方式。
  • 我认为您还需要指定如何“合并” 2 个冲突条目(例如您的 data2 和 data2[id==1][data3_ids] 。我不认为只有 1将执行此操作的函数... id 编写一些贯穿所有内容并应用您想要的规则的东西

标签: python json python-3.x pandas python-2.7


【解决方案1】:

无法评论。因此发布答案。你试过 jsonmerge 吗?

base = {
    "foo": 1,
    "bar": [ "one" ],
 }

head = {
     "bar": [ "two" ],
     "baz": "Hello, world!"
 }


from jsonmerge import merge
result = merge(base, head)

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 2021-08-13
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    相关资源
    最近更新 更多