在python中将json转换为csv中的列表



我想将json文件转换为csv(然后是Excel)。我的json文件的一个示例:

{
"populaires": {
"perfo_indice": {
"perfo_indice_annual": {
"perfo_indice_annual_value": 100.96,
"perfo_percentage_annual_value": 0.96
},
"perfo_indice_monthly": {
"perfo_percentage_monthly_value": 0.96
}
},
"modeles": [
{
"marque": "Austin",
"modele": "Mini",
"cote": {
"cote_2020": 13553,
},
"perfo_modeles": {
"perfo_modeles_annual": {
"perfo_modeles_indice_annual_value": 101.87,
"perfo_modeles_percentage_annual_value": 1.87
},
"perfo_modeles_monthly": {
"perfo_modeles_percentage_monthly_value": 1.87
}
}
},
{
"marque": "Citroën",
"modele": "2CV",
"cote": {
"cote_2020": 11157,
},
"perfo_modeles": {
"perfo_modeles_annual": {
"perfo_modeles_indice_annual_value": 101.92,
"perfo_modeles_percentage_annual_value": 1.92
},
"perfo_modeles_monthly": {
"perfo_modeles_percentage_monthly_value": 1.92
}
}
}]
}]

我希望只输出带有值的键,例如:populaires, perfo_indice_annual_value, perfo_percentage_annual_value, perfo_percentage_monthly_value, marque等。

我有300个modele

I tried with a:

with open('./json/indice_na_2021-01-20.json', encoding='utf-8') as data_model:
data = json.loads(data_model.read())
pt_data1 = open('pt_data1.csv', 'w')
csvwriter = csv.writer(pt_data1)
count = 0
for pt in data:
if count == 0:
header = pt.keys()
csvwriter.writerow(header)
count += 1
csvwriter.writerow(pt.values())
pt_data1.close()

但是。csv只是显示列表。

如何通过"modele">

我建议您一次提取一个所需的键,并一次构造每一行。例如:

import json
import csv

with open('indice_na_2021-01-20.json', encoding='utf-8') as data_model:
data = json.load(data_model)
with open('pt_data1.csv', 'w', newline='', encoding='utf-8') as pt_data1:
csvwriter = csv.writer(pt_data1)
csvwriter.writerow(["marque", "modele", "perfo_modeles_indice_annual_value", "perfo_modeles_percentage_annual_value"])

for model in data["populaires"]["modeles"]:
marque = model["marque"]
modele = model["modele"]
perfo_modeles_indice_annual_value = model["perfo_modeles"]["perfo_modeles_annual"]["perfo_modeles_indice_annual_value"]
perfo_modeles_percentage_annual_value = model["perfo_modeles"]["perfo_modeles_annual"]["perfo_modeles_percentage_annual_value"]

csvwriter.writerow([marque, modele, perfo_modeles_indice_annual_value, perfo_modeles_percentage_annual_value])

这将为您提供以下数据:

marque,modele,perfo_modeles_indice_annual_value,perfo_modeles_percentage_annual_value
Austin,Mini,101.87,1.87
Citroën,2CV,101.92,1.92

相关内容

  • 没有找到相关文章

最新更新