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

如何将Python字典格式化为指定嵌套结构的JSON数据

Python嵌套JSON生成解决方案

核心逻辑说明

你之前的写法是将所有键值对平铺为一级字典,手动填入{作为值的方式无法生成合法的嵌套JSON,json模块会自动处理字典的嵌套序列化,不需要手动构造括号符号。

单条数据实现代码

import json

def bus_line8():
    # 直接构造和目标JSON层级完全对应的嵌套字典结构
    nested_dict = {
        "stations": {
            "Alt-Tegel": {
                "id": 5718454109,
                "name": "Alt-Tegel",
                "label": "Alt-Tegel",
                "position": {
                    "lat": 52.5894565,
                    "lon": 13.2837514
                }
            }
        }
    }
    # 直接写入JSON文件
    with open("bus_line.json", "w", encoding="utf-8") as f:
        json.dump(nested_dict, f, indent=4, ensure_ascii=False)

数千条批量处理代码

如果你已有数千条扁平结构的条目存在列表中,可以用遍历方式批量转换:

import json

def convert_flat_to_nested(flat_item_list):
    output = {"stations": {}}
    for flat_item in flat_item_list:
        station_name = flat_item["name"]
        # 逐个转换扁平条目为嵌套结构
        output["stations"][station_name] = {
            "id": flat_item["id"],
            "name": flat_item["name"],
            "label": flat_item["label"],
            "position": {
                "lat": flat_item["lat"],
                "lon": flat_item["lon"]
            }
        }
    # 写入最终结果文件
    with open("bus_line.json", "w", encoding="utf-8") as f:
        json.dump(output, f, indent=4, ensure_ascii=False)

# 调用示例,flat_item_list替换为你实际的扁平条目列表
# convert_flat_to_nested(flat_item_list)

补充说明

  • 生成的JSON会自动包含正确的括号和层级,不需要手动处理符号
  • 参数ensure_ascii=False和encoding="utf-8"用于兼容非英文字符,避免出现乱码
  • 批量处理时如果有重复的车站名,后面的条目会覆盖前面的,可根据需求调整去重逻辑

内容的提问来源于stack exchange,提问作者Tahiry-R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:36:00