如何合并两个不同的JSON(使用python)

用户9406886

我是python的新手。我想合并两个具有相同对象但键不同的JSON文件。

这是我希望得到的结果的基本示例:

JSON1:

{
 "json1" : {
    "1" : {
        "id": 1,
        "name": "first_artist",
        "imageUrl": "https://1.jpg",
        "genre": "Rap "
      },
    "2" : {
        "id": 2,
        "name": "second_artist",
        "imageUrl": "https://2.jpg",
        "genre": "Hip-Hop"
      }
    }
}

JSON2:

{
 "json2" : {
    "1" : {
        "date": 17/07/19,
        "venue": "venue1"
      },
    "2" : {
        "date": 19/07/19,
        "venue": "venue2"
      }
    }
}

预期的JSON:

{
 "expected_json" : {
    "1" : {
        "id": 1,
        "name": "first_artist",
        "imageUrl": "https://1.jpg",
        "genre": "Rap "
        "date": 17/07/19,
        "venue": "venue1"
      },
    "2" : {
        "id": 2,
        "name": "second_artist",
        "imageUrl": "https://2.jpg",
        "genre": "Hip-Hop"
        "date": 19/07/19,
        "venue": "venue2"
      }
    }
}

有人可以提供提示和方向来实现这一目标吗?谢谢

帕特罗林

您可以将输入简化为:

A.json

{
    "1" : {
        "id": 1,
        "name": "first_artist",
        "imageUrl": "https://1.jpg",
        "genre": "Rap "
    },
    "2" : {
        "id": 2,
        "name": "second_artist",
        "imageUrl": "https://2.jpg",
        "genre": "Hip-Hop"
    }
}

B.json

{
    "1" : {
        "date": "17/07/19",
        "venue": "venue1"
    },
    "2" : {
        "date": "19/07/19",
        "venue": "venue2"
    }
}

并且您必须将19/07/19更改为“ 19/07/19”,才能使其成为有效的json。

现在您可以使用json模块:

import json
#from pprint import pprint


# load json from files
with open('A.json') as A_file:
    A = json.load(A_file)  # returns a dict()
    #print('A:')
    #pprint(A)
with open('B.json') as B_file:
    B = json.load(B_file)
    #print('\nB:')
    #pprint(A)


# get a list of unique keys -> {'1', '2'}
keys = set()
keys.update(A.keys())
keys.update(B.keys())
#print(f'\nkeys: {keys}')


# for each key merge values from dicts A and B
result = {}
for key in keys:
    #print(f'\n{key}:')
    merge = {}
    if key in A:
        merge.update(A[key])
    if key in B:
        merge.update(B[key])
    #pprint(merge)
    result[key] = merge


#print('\nresult:')
#pprint(result)


# write the result to expected.json
with open('expected.json', 'w+') as expected_file:
    expected_file.write(json.dumps(result, sort_keys=True, indent='\t'))

写道:

Expected.json

{
    "1": {
        "date": "17/07/19",
        "genre": "Rap ",
        "id": 1,
        "imageUrl": "https://1.jpg",
        "name": "first_artist",
        "venue": "venue1"
    },
    "2": {
        "date": "19/07/19",
        "genre": "Hip-Hop",
        "id": 2,
        "imageUrl": "https://2.jpg",
        "name": "second_artist",
        "venue": "venue2"
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章