You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python按Value字段合并JSON的CommonTags与index字段问题

JSON按Value分组合并字段修复方案

问题成因

两个bug的来源非常明确:

  • CommonTags出现嵌套列表:合并时直接将整个标签列表作为单个元素追加到目标列表,没有做元素级展开
  • index字段未合并:合并逻辑中遗漏了index字段的收集步骤,没有将同组的index值追加到汇总列表

正确实现逻辑

按以下步骤处理即可得到预期结果:

  • 临时用字典做分组存储,字典的键为对象的Value字段值,值为合并完成后的对象
  • 遍历原始JSON数组的每一项:
    • 如果当前项的Value不在临时字典中,初始化对应分组:复制当前项的CommonTags作为初始标签列表,将当前项的index包装为单元素列表作为初始索引集合,保留其余不需要合并的字段
    • 如果当前项的Value已存在于临时字典:
      • 将当前项CommonTags里的每一个标签,逐个追加到对应分组的CommonTags列表中,不要直接追加整个列表
      • 将当前项的index值追加到对应分组的index列表中
  • 遍历完成后,提取临时字典的所有值即为最终合并结果

代码示例(Python)

raw_data = [
    # 这里替换成你的原始JSON数组数据
    {"Value": "test1", "CommonTags": ["sys", "dev"], "index": 0, "desc": "测试项1"},
    {"Value": "test2", "CommonTags": ["prod"], "index": 1, "desc": "测试项2"},
    {"Value": "test1", "CommonTags": ["dev", "online"], "index": 4, "desc": "测试项1"}
]

group_dict = {}
for item in raw_data:
    current_val = item["Value"]
    if current_val not in group_dict:
        # 初始化分组
        group_dict[current_val] = {
            "Value": current_val,
            "CommonTags": item["CommonTags"].copy(),
            "index": [item["index"]],
            "desc": item["desc"] # 其余非合并字段按实际需求保留
        }
    else:
        # 平铺追加标签,避免嵌套,不需要去重可直接用group_dict[current_val]["CommonTags"].extend(item["CommonTags"])
        for tag in item["CommonTags"]:
            if tag not in group_dict[current_val]["CommonTags"]:
                group_dict[current_val]["CommonTags"].append(tag)
        # 收集index值
        group_dict[current_val]["index"].append(item["index"])

merged_result = list(group_dict.values())

输出效果

上述示例代码运行后得到的结果符合预期:

[
  {
    "Value": "test1",
    "CommonTags": ["sys", "dev", "online"],
    "index": [0, 4],
    "desc": "测试项1"
  },
  {
    "Value": "test2",
    "CommonTags": ["prod"],
    "index": [1],
    "desc": "测试项2"
  }
]

避坑提示

  • 列表追加时区分append()和extend():append()会把传入参数作为单个元素存入,直接传列表就会产生嵌套结构;extend()会把传入的可迭代对象展开后逐个追加,适合不需要去重的标签平铺场景
  • 如果CommonTags不需要去重,直接调用extend()方法即可,不需要循环判断,性能更好
  • index字段每次追加的是当前遍历项的单个index值,不要直接覆盖原有列表

内容的提问来源于stack exchange,提问作者devPie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.18 16:15:43