[英]How can I change the format of a JSON output from iterating through a python dictionary
i'm trying to change the format of a json file from:我正在尝试从以下位置更改 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"
}
]
}
to:至:
[
{
"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": ""
}
}
]
I'have build this python script, but I'm struggling to get the expected format.我已经构建了这个 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)
my output:我的 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": ""
}
},
}
I tried to iterate through the dictionary with several different methods and I'm always failing to get the right JSON.我试图用几种不同的方法遍历字典,但总是找不到正确的 JSON。 This example seems to be the closest.
这个例子似乎是最接近的。
Is there a better way to iterate through a dictionary to change the format of a python script?是否有更好的方法来遍历字典以更改 python 脚本的格式?
Putting results into a list should work:将结果放入列表中应该有效:
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)
Nb it might be a good idea to save the result as a dictionary:注意,将结果保存为字典可能是个好主意:
with open('target.json', 'w') as f:
json.dump({'items': result}, f)
as it will have been a bit more future proof.因为这将是一个更多的未来证明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.