如何去除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
相关产品推荐
相关产品推荐

