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

加载多行JSON文件时返回空列表,求问题排查及解决方法

问题排查与解决方案

问题描述

尝试读取每行一个JSON对象的data.json文件,文件内容如下:

{"John" : "doe", "Age" : "Unknown"}
{"kat" : "doe", "Age" : "Unknown"}
{"Brian" : "doe", "Age" : "Known"}

编写的Python代码运行后始终返回空列表:

dt = []
with open("data.json") as file:
for line in file.readlines():
    temp = json.loads(line)
    dt.append(temp)
print(dt)

问题原因

  1. 缩进错误:Python是严格依赖缩进的语言,for循环语句没有缩进在with代码块内,导致循环未被执行。with块结束后文件已关闭,后续循环无法读取到任何内容,最终dt保持为空列表。
  2. 潜在隐患:若文件存在空行(比如末尾空行),json.loads(line)会抛出JSON解析错误,不过当前导致空列表的直接原因是缩进问题。

修复方案

方案1:修正缩进并处理空行

import json

dt = []
with open("data.json") as file:
    for line in file.readlines():
        # 跳过空行,避免解析报错
        stripped_line = line.strip()
        if stripped_line:
            temp = json.loads(stripped_line)
            dt.append(temp)
print(dt)

方案2:简化读取方式(直接迭代文件对象)

无需调用readlines(),直接迭代文件对象更高效,同时处理空行:

import json

dt = []
with open("data.json") as file:
    for line in file:
        stripped_line = line.strip()
        if stripped_line:
            dt.append(json.loads(stripped_line))
print(dt)

运行结果

修复后代码会正确输出:

[{'John': 'doe', 'Age': 'Unknown'}, {'kat': 'doe', 'Age': 'Unknown'}, {'Brian': 'doe', 'Age': 'Known'}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 10:48:16