我有从URL获取的数据,我得到一个包含嵌套LIST和DICTIONARY数据的JSON。现在我想将这些数据写入CSV文件。
{
"type": "abs",
"format": "cdg",
"version": "6",
"data": {
"fff": {
"version": "6",
"id": "fff",
"key": "266",
"name": "fff",
"title": "the Darkin Blade"
"info": {
"attack": 8,
"defense": 4,
"magic": 3,
"difficulty": 4
},
"tags": [
"Fighter",
"Tank"
],
"partype": "BloodWell",
"stats": {
"hp": 537.8,
"hpperlevel": 85,
"mp": 105.6
}
},
"ggg": {
"version": "6",
"id": "ggg",
"key": "103",
"name": "ggg"
"info": {
"attack": 3,
"defense": 4,
"magic": 8,
"difficulty": 5
},
"tags": [
"Mage",
"Assassin"
],
"partype": "MP",
"stats": {
"hp": 514.4,
"hpperlevel": 80,
"mp": 334
}
}
}
如何遍历所有嵌套值并将其写入CSV文件? 我希望所有数据的输出如下:
type format version data__ data__|__version data__|__id info_attack
abs cdg 6 fff 6.13.1 fff 8
abs cdg 6 ggg 6.13.1 ggg 3
答案 0 :(得分:1)
import csv
import json
json_file='sample.json'
with open(json_file, 'r') as json_data:
x = json.load(json_data)
f = csv.writer(open("test.csv", "w"))
f.writerow(["type", "format", "version", "data__","data__|__version","data__|__id","info_attack","info_defense"])
types=x["type"]
format=x["format"]
root_version=x["version"]
for key in x["data"]:
f.writerow([types,
format,
root_version,
x["data"][key]["name"],
x["data"][key]["version"],
x["data"][key]["id"],
x["data"][key]["info"]["attack"],
x["data"][key]["info"]["defense"]])
输出
type,format,version,data__,data__|__id
abs,cdg,6,fff,fff
abs,cdg,6,ggg,ggg