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

Python实现类JS JSON.stringify函数:嵌套字典递归格式化问题

解决嵌套字典格式化问题

你的代码核心问题有两个:

  • 递归调用stringify后没用到返回值,反而直接用str()处理嵌套字典,导致输出Python默认的字典字符串
  • 嵌套字典内部的内容没有增加对应层级的缩进,格式不符合预期

下面是修复后的代码:

PRIMITIVES = [str, float, int, bool]
PLAINS = [list, tuple, set]


def stringify(value, replacer: str = ' ', spaces_count: int = 1) -> str:
    # 处理基础类型
    if type(value) in PRIMITIVES:
        return str(value)
    # 处理列表、元组、集合
    elif type(value) in PLAINS:
        return str(value)
    # 处理字典(包括嵌套字典)
    else:
        result = []
        opening_bracket = '{'
        closing_bracket = '}'
        indent = replacer * spaces_count
        result.append(opening_bracket)
        
        # 直接对字典键排序,无需转set(字典键本身唯一)
        for key in sorted(value.keys()):
            val = value[key]
            # 处理值:如果是基础或集合类型直接转字符串,否则递归调用
            if type(val) in PRIMITIVES or type(val) in PLAINS:
                val_str = str(val)
            else:
                # 递归获取嵌套字典的格式化字符串
                val_str = stringify(val, replacer, spaces_count)
            
            # 处理嵌套内容的缩进:拆分递归结果的每一行,除了第一行的{,其余行增加缩进
            lines = val_str.split('\n')
            if len(lines) > 1:
                # 第一行保持不变,后续每行加缩进
                indented_lines = [lines[0]] + [indent + line for line in lines[1:]]
                val_str = '\n'.join(indented_lines)
            
            result.append(f'{indent}{str(key)}: {val_str}')
        
        result.append(closing_bracket)
        return '\n'.join(result)

测试你的示例输入:

data = { "hello": "world", "is": True, "nested": { "count": 5 } }
print(stringify(data, spaces_count=2))

输出结果:

{
  hello: world
  is: True
  nested: {
    count: 5
  }
}

关键修改说明:

  1. 递归返回值利用:调用stringify(val, replacer, spaces_count)后接收返回值,不再用str(val)
  2. 嵌套缩进处理:将递归得到的嵌套字典字符串按行拆分,给除了首行的所有行添加当前层级的缩进,保证嵌套结构的格式正确
  3. 键排序优化:直接用sorted(value.keys())替代sorted(set(value)),避免不必要的类型转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:15:27