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

如何通过遍历Python字典实现指定JSON格式转换?

问题

我需要将以下格式的JSON文件:

{"ordnungsrufe": [{"date": "1961-04-18", "president": "Prof. D. Dr. Eugen Gerstenmaier (CDU/CSU)", "wp": "3", "protocol": "Protokoll der 154. Sitzung des 3. Deutschen Bundestages", "source": "https://dserver.bundestag.de/btp/03/03154.pdf", "calledOutName": "Adolf Ludwig, MdB", "calledOutParty": "SPD"}]}

转换为:

[{"calledOut": {"name": "Adolf Ludwig, MdB", "party": "SPD"}, "date": "1961-04-18", "president": "Prof. D. Dr. Eugen Gerstenmaier (CDU/CSU)", "source": {"pdf": "https://dserver.bundestag.de/btp/03/03154.pdf", "sectionFrom": "", "sectionTo": "", "linkToVideo": ""}}]

我写了Python脚本,但输出是以被叫出姓名为键的对象结构,得不到预期的数组格式:

import json
import codecs

data = json.load(codecs.open('data.json', 'r', 'utf-8-sig'))
ordnungsruf = {}

for person in data['ordnungsrufe']:
    ordnungsruf[person['calledOutName']] = {
        "calledOut" : {
            "name": person["calledOutName"],
            "party": person["calledOutParty"]
        },
        "date": person["date"],
        "president" : person["president"],
        "source" : {
          "pdf": person["source"],
          "sectionFrom": "",
          "sectionTo": "",
          "linkToVideo": "",
        }
    }

with open('ordnungsrufe_ordered.json', 'w') as json_file:
  json.dump(ordnungsruf, json_file, indent=2)

当前输出:

{"Adolf Ludwig, MdB": {"calledOut": {"name": "Adolf Ludwig, MdB", "party": "SPD"}, "date": "1954-12-08", "president": "Prof. D. Dr. Eugen Gerstenmaier (CDU/CSU)", "source": {"pdf": "https://dserver.bundestag.de/btp/02/02059.pdf", "sectionFrom": "", "sectionTo": "", "linkToVideo": ""}}}

试过多种遍历方法都没成功,这个版本最接近预期,求更优实现方式?


解决方法

问题核心是你初始化了字典ordnungsruf = {},但预期输出是数组(Python中的列表),只需将容器类型改为列表,再把每个转换后的条目追加进去即可。

修正后的脚本:

import json
import codecs

data = json.load(codecs.open('data.json', 'r', 'utf-8-sig'))
# 将容器从字典改为列表,匹配预期的数组结构
ordnungsruf = []

for person in data['ordnungsrufe']:
    # 构造单个符合格式要求的条目字典
    entry = {
        "calledOut": {
            "name": person["calledOutName"],
            "party": person["calledOutParty"]
        },
        "date": person["date"],
        "president": person["president"],
        "source": {
            "pdf": person["source"],
            "sectionFrom": "",
            "sectionTo": "",
            "linkToVideo": ""
        }
    }
    # 将条目追加到列表中
    ordnungsruf.append(entry)

# 写入文件时指定编码,避免特殊字符转义
with open('ordnungsrufe_ordered.json', 'w', encoding='utf-8') as json_file:
    json.dump(ordnungsruf, json_file, indent=2, ensure_ascii=False)

关键改动说明

  1. 容器类型调整:把ordnungsruf从字典改为列表,直接对应JSON的数组结构。
  2. 条目追加逻辑:循环中构造好单个条目后,用append()方法添加到列表末尾,保证输出是数组格式。
  3. 编码优化:写入时指定encoding='utf-8'和ensure_ascii=False,避免德语特殊字符被转义为ASCII编码。

这个实现逻辑简洁直接,完全匹配你需要的输出格式,同时自动忽略了原数据中不需要的wp和protocol字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:18:27