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

如何去除JSON文件列表中的换行?Python实现列表单行格式化

解决方案

可以通过Python的json模块自定义格式化逻辑,精准将指定列表压缩为单行,具体代码如下:

import json

# 读取原始JSON文件
with open('input.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# 将目标列表转换为紧凑的单行字符串
bird_answer_compact = json.dumps(data["BIRD_answer"], separators=(",", ":"))
my_answer_compact = json.dumps(data["my_answer"], separators=(",", ":"))

# 拼接成符合要求的JSON格式内容
formatted_json = (
    "{\n"
    f'    "BIRD_answer":{bird_answer_compact},\n'
    f'    "my_answer":{my_answer_compact}\n'
    "}"
)

# 写入到输出文件
with open('output.json', 'w', encoding='utf-8') as f:
    f.write(formatted_json)

代码说明:

  • json.dumps(..., separators=(",", ":")):通过指定分隔符去掉列表元素间的空格与换行,将列表压缩为单行紧凑格式。
  • 手动拼接JSON结构:确保整体格式符合需求,目标键值对保持缩进并单独成行,其他结构(如大括号)也按预期排版。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 03:15:15