在python中合并两个json对象

您所在的位置:网站首页 json字符串合并 在python中合并两个json对象

在python中合并两个json对象

2023-12-31 18:29| 来源: 网络整理| 查看: 265

我建议您为了自己的利益去学习Python的基础知识,因为您似乎不理解为什么您的代码不能工作。

import json # We have two dictionaries to combine json_obj_1 = {"a": [1,2], "b":[2,3], 'c': [1,2,3]} json_obj_2 = {"a": [3,4], 'd':[4,2], 'e': [4,2,2]}

合并后的字典将存储在此处

hold_json_obj = {}

不要担心,实际上并不是那么复杂。逐行阅读代码,并附上注释,您就会明白。

# We'll loop through every item in the json_obj_1 dictionary for item_1 in json_obj_1: # We'll also loop through every item in the json_obj_2 dictionary for item_2 in json_obj_2: # Now let's compare whether they are the same KEYS (not values) if item_1 == item_2: # if they match, we create a list to store the array hold_array = [] hold_array.extend(json_obj_1[item_1]) hold_array.extend(json_obj_2[item_1]) # finally putting the array to our hold_json_obj hold_json_obj[item_1] = hold_array else: # if they don't match, check if the key already exists in the # hold_json_obj because we might be iterating json_obj_2 for the second time. if item_2 not in hold_json_obj: #add the ummatched array to hold_json_obj hold_json_obj[item_2] = json_obj_2[item_2]

现在只需使用update方法更新json_obj_1。更新函数是必需的,因为如果json_obj_1有json_obj_2没有的键,那么我们可能在上面的循环中遗漏了它们。

json_obj_1.update(hold_json_obj) print(json_obj_1)

这是打印显示的内容。

{'a': [1, 2, 3, 4], 'b': [2, 3], 'c': [1, 2, 3], 'd': [4, 2], 'e': [4, 2, 2]}


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3