Python使用json.dump导出JSON文件时缩进不符合预期如何解决
问题原因
Python 标准库 json 模块的 indent 参数会对所有嵌套容器(字典、列表)统一应用换行缩进规则,没有提供原生参数单独控制列表内元素不换行。你之前设置的 sort_keys=False 仅控制字典键是否按字母序排序,和换行缩进逻辑完全无关,因此不会改变输出格式。
额外说明:标准 JSON 语法要求键和字符串必须使用双引号,你贴出的单引号示例不符合 JSON 规范,json.dump 默认输出的是合规双引号内容。
解决方案
通过继承 json.JSONEncoder 重写序列化逻辑,识别一级列表并将其压缩为单行输出即可,可直接运行的代码如下:
import json class CompactListEncoder(json.JSONEncoder): def iterencode(self, o, _one_shot=False): list_depth = 0 buffer = [] in_compact_list = False for chunk in super().iterencode(o, _one_shot=_one_shot): if chunk == '[': list_depth += 1 if list_depth == 1: in_compact_list = True buffer = ['['] continue if in_compact_list: buffer.append(chunk) if chunk == ']': list_depth -= 1 if list_depth == 0: # 清除列表内部的换行、缩进冗余空白 compact_content = ''.join(buffer).replace('\n', '').replace(' ', ' ') yield compact_content in_compact_list = False buffer = [] continue yield chunk null = None json_data = { 'A': [null, null], 'B': [null, null], 'C': [null, null] } # 写入文件时指定自定义编码器 with open('Export.json', 'w', encoding='utf-8') as outfile: json.dump(json_data, outfile, indent=2, cls=CompactListEncoder)
运行后导出的文件内容完全匹配预期格式:
{ "A": [null, null], "B": [null, null], "C": [null, null] }
补充说明
- 如果你的JSON结构非常固定,也可以不设置
indent参数,手动拼接字符串实现格式控制,但灵活度极低,不推荐使用。 - 如果需要对更深层的列表做紧凑处理,只需要调整
list_depth == 1的判断阈值即可。
内容的提问来源于stack exchange,提问作者Akascape
相关产品推荐
相关产品推荐

