Python:如何合并3个JSON文件,其中一些数据具有相同的键

mrwjdhj3  于 2023-01-27  发布在  Python
关注(0)|答案(1)|浏览(224)

Python:如何合并3个JSON文件,其中一些数据具有相同的键,我想保留第三个文件json文件并将它们合并为一个,我有三个json文件:

file1.json
{
  "A111": {
       "KEY1" : "AAA1"
       "KEY2" : "AAA2"
  }
}

file2.json
{
  "B222": {
       "KEY1" : "BBB1"
       "KEY2" : "BBB2"
  }
}

file3.json
{
  "A111": {
       "KEY1" : "CCC1"
       "KEY2" : "CCC2"
  }
}

#================================================#
I NEED THE OUTPUT OF MERGED JSON FILE:
filemerged.json
{
  "A111": {
       "KEY1" : "CCC1"
       "KEY2" : "CCC1"
  }
  "B222": {
       "KEY1" : "BBB1"
       "KEY2" : "BBB2"
  }
}

需要megre他们,并保持最后的json更新

9rnv2umw

9rnv2umw1#

在python中,Json的行为也类似于字典。
您可以简单地使用字典的update()

j1={
  "A111": {
       "KEY1" : "AAA1",
       "KEY2" : "AAA2"
  }
}

j2={
  "B222": {
       "KEY1" : "BBB1",
       "KEY2" : "BBB2"
  }
}

j3={
  "A111": {
       "KEY1" : "CCC1",
       "KEY2" : "CCC2"
  }
}

j3.update(j2)

print(j3)
{'A111': {'KEY1': 'CCC1', 'KEY2': 'CCC2'},
 'B222': {'KEY1': 'BBB1', 'KEY2': 'BBB2'}}

相关问题