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

Python循环向JSON文件追加列表时格式异常的解决方法

解决JSON文件数组合并更新问题

你的问题核心是直接用追加模式(a)写入JSON,导致每次新增的数组和原有数组拼接成无效的JSON结构。正确的做法是先读取现有数据,合并新数据后再整体覆盖写入,具体实现如下:

完整代码实现

import json
import os

# 生成要添加的新数据(沿用你的列表生成逻辑)
new_entries = [
    {'preis': price, 'plz': plz, 'zimmer': room, 'wohnflaeche': sqr}
    for price, plz, room, sqr in zip(priceList, plzList, roomList, sqrList)
]

file_path = 'immodata.json'
# 初始化现有数据为空列表
existing_entries = []

# 读取已有数据(处理文件不存在/为空的情况)
if os.path.exists(file_path) and os.path.getsize(file_path) > 0:
    with open(file_path, 'r', encoding='utf-8') as file:
        try:
            existing_entries = json.load(file)
        except json.JSONDecodeError:
            # 若文件内容损坏,重置为空列表
            existing_entries = []

# 合并新数据到现有数组
existing_entries.extend(new_entries)

# 覆盖写入完整的JSON数组
with open(file_path, 'w', encoding='utf-8') as file:
    json.dump(existing_entries, file, ensure_ascii=False, indent=4)

关键说明

  • 避免追加模式:用w模式覆盖写入,确保文件始终是一个合法的JSON数组。
  • 处理边界情况:检查文件是否存在且非空,同时捕获JSON解析错误,防止文件损坏导致程序崩溃。
  • 正确合并数据:用extend()将新数据的每个元素追加到现有数组中,而不是用append()(后者会把整个新列表作为单个元素加入)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:10:49