Python中如何按字段映射合并两个JSON对象并追加对应value
Python实现两个JSON对象按字段关联合并
实现思路
以两个数据集共有的field字段为关联键,先将次数据集转换为field: value的索引字典提升匹配效率,再遍历主数据集的所有表单项,将匹配到的value属性追加到对应对象中,最终得到合并结果。
完整可运行代码
import json import copy # 原始主数据集(若输入为JSON字符串,可通过json.loads()解析为Python字典) primary = { "form-fields": [ {"type": "text", "x-position": 0, "y-position": 0, "field": "buyer-1"}, {"type": "text", "x-position": 0, "y-position": 10, "field": "buyer-2"} ] } # 原始次数据集 secondary = { "form-data": [ {"field": "buyer-1", "value": "John Smith"}, {"field": "buyer-2", "value": "Susan Smith"} ] } # 如需保留原始主数据集不被修改,可先做深拷贝操作 # merged_result = copy.deepcopy(primary) merged_result = primary # 构建次数据集的字段-值映射表 value_map = {item["field"]: item["value"] for item in secondary["form-data"]} # 遍历主数据集追加匹配的value for form_item in merged_result["form-fields"]: match_value = value_map.get(form_item["field"]) if match_value is not None: form_item["value"] = match_value # 若需要输出为JSON格式字符串,可执行以下代码 # print(json.dumps(merged_result, indent=2, ensure_ascii=False))
运行结果
执行代码后merged_result的值和预期完全一致:
{ "form-fields": [ {"type": "text", "x-position": 0, "y-position": 0, "field": "buyer-1", "value": "John Smith"}, {"type": "text", "x-position": 0, "y-position": 10, "field": "buyer-2", "value": "Susan Smith"} ] }
注意事项
- 代码对次数据集中不存在匹配字段的场景做了兼容,不会抛出键错误,未匹配的表单项会保留原有结构
- 字典索引的匹配方式时间复杂度为O(n),远优于双层循环遍历的O(n*m),适合表单项数量较多的场景
- 若不希望修改原始主数据集对象,务必使用
copy.deepcopy()做深拷贝后再操作副本,避免原始数据被污染
内容的提问来源于stack exchange,提问作者Parker
相关产品推荐
相关产品推荐

