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

Python中如何正确将字典列表转存为合法JSON文件?

解决Python字典列表生成合法JSON文档的问题

你遇到的JSONDecodeError,根源是循环逐个dump字典时,文件中会生成多个独立的JSON对象,而标准JSON文档要求整体是单一合法结构(如数组、对象),多对象共存不符合规范,导致解析失败。以下针对不同场景给出解决方案:

方案1:直接dump整个列表(内存可容纳场景)

直接将完整的items列表传入json.dump(),生成合法的JSON数组,读取时可直接用json.load()解析:

import json

items = [{'key': {'Brand': 'Tesla', 'Date': '2020'}, 'Total': 56, 'my_vin': '#468123'},
         {'key': {'Brand': 'Toyota', 'Date': '2022'}, 'Total': 6, 'my_vin': '#468210'},
         {'key': {'Brand': 'Audi', 'Date': '2023'}, 'Total': 1, 'my_vin': '#468132'}]

# 写入合法JSON文件
with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(items, f, indent=2)  # indent可选,用于格式化输出

# 读取验证
with open('output.json', 'r', encoding='utf-8') as f:
    loaded_items = json.load(f)
print(loaded_items)

方案2:JSON Lines格式(超长列表场景)

若items规模极大(如百万级元素),一次性加载会占用过多内存,可采用**JSON Lines(.jsonl)**格式:每行存储一个独立JSON对象,写入/读取时逐行处理,内存压力更低:

写入代码

import json

items = [...]  # 你的超长字典列表

with open('output.jsonl', 'w', encoding='utf-8') as f:
    for item in items:
        json.dump(item, f)
        f.write('\n')  # 每行结尾添加换行符

读取代码

loaded_items = []
with open('output.jsonl', 'r', encoding='utf-8') as f:
    for line in f:
        if line.strip():  # 跳过空行
            loaded_items.append(json.loads(line))
print(loaded_items)

方案选择建议

  • 内存可容纳时优先选方案1,生成标准JSON数组,兼容性更强;
  • 处理超大数据集时选方案2,兼顾合法性与内存效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:55:23