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

如何使用jq将指定JSON对象合并到多个目标JSON对象中?

多JSON对象合并解决方案

问题场景

你的JSON文件包含多个独立对象:前两个对象包含name、url、id、gender字段,最后一个对象包含brand和cats数组字段,需要将最后一个对象的字段合并到前两个对象中,之前合并操作出现字段值为null的问题。

可行解决步骤(以Python为例)

情况1:JSON文件为数组格式(对象用[]包裹)

如果你的JSON文件是标准数组结构,比如:

[
  {"name": "Alice", "url": "alice.com", "id": 1, "gender": "female"},
  {"name": "Bob", "url": "bob.com", "id": 2, "gender": "male"},
  {"brand": "TechCorp", "cats": ["electronics", "gadgets"]}
]

可以用以下代码合并:

import json

# 读取并加载JSON数组
with open('your_file.json', 'r', encoding='utf-8') as f:
    json_data = json.load(f)

# 提取最后一个对象的合并字段
extra_fields = json_data[-1]

# 遍历前两个对象,合并字段
for target_obj in json_data[:-1]:
    # 使用update方法安全合并,仅添加新字段,不覆盖原有内容
    target_obj.update(extra_fields)

# 输出合并后的结果(或写入新文件)
for obj in json_data[:-1]:
    print(json.dumps(obj, indent=2, ensure_ascii=False))

情况2:JSON文件为多行独立对象(无外层数组)

如果你的JSON文件每行是一个独立JSON对象,比如:

{"name": "Alice", "url": "alice.com", "id": 1, "gender": "female"}
{"name": "Bob", "url": "bob.com", "id": 2, "gender": "male"}
{"brand": "TechCorp", "cats": ["electronics", "gadgets"]}

需要逐行解析并合并:

import json

target_objs = []
extra_fields = None

# 逐行读取并解析每个JSON对象
with open('your_file.json', 'r', encoding='utf-8') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        current_obj = json.loads(line)
        # 判断是否为提供合并字段的对象
        if all(key in current_obj for key in ['brand', 'cats']):
            extra_fields = current_obj
        else:
            target_objs.append(current_obj)

# 执行合并
if extra_fields:
    for obj in target_objs:
        obj.update(extra_fields)

# 查看结果
for obj in target_objs:
    print(json.dumps(obj, indent=2, ensure_ascii=False))

常见问题排查

  • 合并出现null通常是因为:
    1. 未正确获取到最后一个对象的字段(比如读取时遗漏了最后一行,或解析失败)
    2. 合并时使用了错误的赋值方式(比如直接赋值obj['brand'] = extra_fields['brand']但extra_fields未正确初始化)
    3. JSON文件存在格式错误(比如字段名拼写不一致,或对象语法错误)
  • 建议先打印extra_fields确认是否正确获取到brand和cats字段,再执行合并操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:01:22