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

如何用Python将含嵌套数组的JSON数据单行写入文件?

如何让JSON嵌套数组保持单行写入文件?

问题背景

想要将JSON数据写入文件时,让嵌套的长数组保持单行格式,期望输出示例:

{"test1": {"key1": [[0, 40], [2, 42], [4, 44], [6, 46], [8, 48], [10, 50], [12, 52],......],"key2": [[1, 41], [3, 43], [5, 45], [7, 47], [9, 49], [11, 51], [13, 53],......]},"test2": {"key1": [[0, 52], [1, 53], [2, 54], [3, 55], [4, 56], [5, 57], [6, 58],......],"key2": [[26, 78], [27, 79], [28, 80], [29, 81], [30, 82], [31, 83],......]}}

但使用标准库的json.dump并设置indent=2时,嵌套数组会被拆分成多行,代码如下:

with open("test.json", 'w') as f:
    json.dump(result, f, ensure_ascii=False, indent=2)

解决方案

方法1:自定义JSON编码器

继承json.JSONEncoder重写编码逻辑,让指定的嵌套数组保持单行,其他结构正常缩进:

import json

class CustomJSONEncoder(json.JSONEncoder):
    def encode(self, obj):
        # 处理二维数组(可根据实际需求调整判断条件)
        if isinstance(obj, list) and all(isinstance(item, list) and len(item) == 2 for item in obj):
            return '[' + ', '.join(self.encode(item) for item in obj) + ']'
        # 处理字典,添加缩进
        elif isinstance(obj, dict):
            lines = []
            for key, val in obj.items():
                lines.append(f'"{key}": {self.encode(val)}')
            return '{\n  ' + ',\n  '.join(lines) + '\n}'
        # 其他类型用默认编码逻辑
        return super().encode(obj)

# 使用自定义编码器写入
with open("test.json", 'w') as f:
    json.dump(result, f, ensure_ascii=False, cls=CustomJSONEncoder)

方法2:手动格式化JSON字符串

先生成无缩进的JSON字符串,再对字典结构手动添加缩进,数组部分保持单行:

import json

def format_json(raw_str, indent='  '):
    level = 0
    formatted = []
    in_array = False
    for char in raw_str:
        if char == '{' and not in_array:
            level += 1
            formatted.append('{\n' + indent * level)
        elif char == '}' and not in_array:
            level -= 1
            formatted.append('\n' + indent * level + '}')
        elif char == '[':
            in_array = True
            formatted.append(char)
        elif char == ']':
            in_array = False
            formatted.append(char)
        elif char == ',' and not in_array:
            formatted.append(',\n' + indent * level)
        else:
            formatted.append(char)
    return ''.join(formatted)

# 生成无缩进JSON,再格式化
raw_json = json.dumps(result, ensure_ascii=False)
formatted_json = format_json(raw_json)

with open("test.json", 'w') as f:
    f.write(formatted_json)

方法3:使用第三方JSON库

比如simplejson,它支持更灵活的格式化参数,先安装库:

pip install simplejson

然后使用如下代码:

import simplejson as json

with open("test.json", 'w') as f:
    json.dump(result, f, ensure_ascii=False, indent=2, item_separator=', ')

注意:该方法的效果取决于库的实现,建议测试后再使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:55:22