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

如何在Python中读取多JSON拼接文件并合并所有列表为一个对象?

合并多顶级JSON文件中的items列表

你的代码失败是因为json.load()只能解析单个顶级JSON对象,而你的文件包含多个独立的JSON对象,不属于合法的单一JSON结构,因此会抛出解析错误。

可以使用json.JSONDecoder的raw_decode()方法,它能从字符串中解析出第一个完整的JSON对象,并返回该对象以及解析结束的位置索引。通过循环调用这个方法,就能逐个解析文件中的所有JSON对象,最终合并所有items列表。

完整实现代码

import json

def merge_json_items(file_path):
    combined_items = []
    decoder = json.JSONDecoder()
    
    # 读取文件全部内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read().strip()
    
    # 循环解析每个JSON对象
    while content:
        # 解析当前第一个JSON对象,返回对象和结束索引
        json_obj, end_idx = decoder.raw_decode(content)
        # 将当前JSON的items列表合并到总列表中
        combined_items.extend(json_obj.get('items', []))
        # 截取剩余未解析的内容,去除空白字符
        content = content[end_idx:].strip()
    
    return combined_items

# 使用示例
json_file_path = "your_json_file.json"
merged_result = merge_json_items(json_file_path)
# 输出合并后的结果
print(merged_result)

补充说明

  • 该方法不依赖JSON对象的排版格式(不管每个JSON是多行还是单行),只要每个JSON对象是合法的独立结构就能解析。
  • 如果某个JSON对象中没有items键,get('items', [])会返回空列表,避免程序报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:40:43