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

如何使用json.dump保存无首尾方括号的JSON文件

如何保存JSON时移除外层的方括号[]

问题背景

需要将DataFrame导出为无外层方括号的JSON格式,仅保留逗号分隔的多个JSON对象。当前代码生成的是标准JSON数组(带首尾[]),且数据包含复杂嵌套字典结构;尝试to_json(orient='records', lines=True)时触发JSONDecodeError。

示例数据:

import pandas as pd
import json

df = pd.DataFrame({'name' : ['abc', 'pqr', 'xzy'],
                  'score' : [85, 90, 80],
                  'address' : ['ab street', 'pq street', 'xy ave']})

当前实现代码:

jl = json.loads(df.to_json(orient='records'))
f = open('expfile.json', 'w')
json.dump(jl, f, indent = 4)
f.close()

解决方案

方案1:直接处理JSON字符串(简单高效)

利用to_json生成带数组的JSON字符串,通过切片移除首尾的[],同时处理缩进带来的空格/换行:

import pandas as pd

# 生成带缩进的JSON数组字符串
json_str = df.to_json(orient='records', indent=4)
# 去除首尾的[]及多余空白字符
trimmed_json = json_str.strip()[1:-1].strip()

with open('expfile.json', 'w') as f:
    f.write(trimmed_json)

方案2:逐个序列化对象拼接(适配复杂嵌套)

如果担心字符串切片误操作嵌套结构中的[],可以逐行序列化后拼接:

import pandas as pd
import json

json_objects = []
for _, row in df.iterrows():
    # 将行转为字典,序列化时自动处理嵌套结构
    obj_json = json.dumps(row.to_dict(), indent=4)
    json_objects.append(obj_json)

# 用逗号+换行拼接所有JSON对象
final_content = ',\n'.join(json_objects)

with open('expfile.json', 'w') as f:
    f.write(final_content)

关于lines=True的报错说明

to_json(orient='records', lines=True)生成的是每行一个独立JSON对象的文本,不属于标准JSON规范(标准JSON仅允许单个顶级对象/数组),因此用json.load()直接读取会报错。若要读取这类文件,需逐行解析:

objects = []
with open('expfile.json', 'r') as f:
    for line in f:
        obj = json.loads(line.strip())
        objects.append(obj)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 07:40:29