簡體   English   中英

如何通過迭代 python 字典來更改 JSON output 的格式

[英]How can I change the format of a JSON output from iterating through a python dictionary

我正在嘗試從以下位置更改 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'))
#print(data)

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)

我的 output:

{
  "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": ""
    }
  },
}

我試圖用幾種不同的方法遍歷字典,但總是找不到正確的 JSON。 這個例子似乎是最接近的。

是否有更好的方法來遍歷字典以更改 python 腳本的格式?

將結果放入列表中應該有效:

result = []
for item in data['ordnungsrufe']:
    result.append({
        'calledOut': {
            'name': item['calledOutName'],
            'party': item['calledOutParty']
        },
        'date': item['date'],
        'president': item['president'],
        'source': {
            'pdf': item['source'],
            'sectionFrom': '',
            'sectionTo': '',
            'linkToVideo': ''
        }
    })
print(result)

注意,將結果保存為字典可能是個好主意:

with open('target.json', 'w') as f:
    json.dump({'items': result}, f)

因為這將是一個更多的未來證明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM