Python - 将json输出解析为CSV

时间:2017-09-07 15:27:30

标签: python json csv

我在python中解析了一个json文件,并在屏幕上打印结果。

但是,我还希望将结果输出到csv文件,就像它们出现在屏幕上一样。

这是我的代码:

import json

with open('euroinc.json') as json_data:
    d = json.load(json_data)
    for p in d['results']:
        print(p['sedol']+','+p['company']+','+p['name']+','+ p['unitType']+','+p['perf48t60m']+','+p['perf36t48m']+','+p['perf24t36m']+','+p['perf12t24m']+','+p['perf12m']+','+p['initialCharge']+','+p['netAnnualCharge'])

任何帮助将不胜感激! 谢谢, 克雷格

更新:这是json示例:

{
  "results": [
    {
      "sector": "Europe Including UK", 
      "perf48t60m": "n/a", 
      "discountedCode": "", 
      "price_buy": "0", 
      "plusFund": false, 
      "unitType": "Accumulation", 
      "perf6m": "6.35%", 
      "perf36t48m": "11.29%", 
      "loaded": "Unbundled", 
      "fundSize": "2940.1", 
      "annualCharge": "1.07", 
      "netAnnualCharge": "1.07", 
      "sedol": "B7BW9Y0", 
      "perf24t36m": "0.25%", 
      "annualSaving": "0.00", 
      "updated": "06/09/2017", 
      "incomeFrequency": "N/a", 
      "perf60m": "n/a", 
      "perf12t24m": "12.97%", 
      "company": "BlackRock", 
      "initialCharge": "0.00", 
      "paymentType": "Dividend", 
      "perf3m": "0.32%", 
      "name": "BlackRock Global European Value (D2 GBP)", 
      "perf12m": "19.37%", 
      "price_change": "-39.00", 
      "yield": "0.00", 
      "price_sell": "6569.00", 
      "perf36m": "35.19%", 
      "numHoldings": "51"
    }, 
    {
      "sector": "Europe Including UK", 
      "perf48t60m": "22.01%", 
      "discountedCode": "", 
      "price_buy": "0", 
      "plusFund": false, 
      "unitType": "Income", 
      "perf6m": "7.81%", 
      "perf36t48m": "9.61%", 
      "loaded": "Unbundled", 
      "fundSize": "566.1", 
      "annualCharge": "0.30", 
      "netAnnualCharge": "0.30", 
      "sedol": "B76VTR5", 
      "perf24t36m": "-3.95%", 
      "annualSaving": "0.00", 
      "updated": "06/09/2017", 
      "incomeFrequency": "Quarterly", 
      "perf60m": "77.38%", 
      "perf12t24m": "15.38%", 
      "company": "Vanguard", 
      "initialCharge": "0.00", 
      "paymentType": "Dividend", 
      "perf3m": "0.74%", 
      "name": "Vanguard SRI European Stock", 
      "perf12m": "19.69%", 
      "price_change": "-21.37", 
      "yield": "2.79", 
      "price_sell": "15800.81", 
      "perf36m": "32.65%", 
      "numHoldings": "502"
    }
  ]
}

2 个答案:

答案 0 :(得分:1)

这将写入带有标题的CSV文件。注意需要fieldnamesextrasaction参数来指定列的顺序,并在有额外的字典条目时防止出错。

#!python2
import json
import csv

with open('euroinc.json') as json_data:
    d = json.load(json_data)

# with open('out.csv','w',newline='') as f:  # Python 3 version
with open('out.csv','wb') as f:
    w = csv.DictWriter(f,
                       fieldnames='sedol company name unitType perf48t60m perf36t48m perf24t36m perf12t24m perf12m initialCharge netAnnualCharge'.split(),
                       extrasaction='ignore')
    w.writeheader()
    # Ways to use a different header.
    # Note the direct write should use \r\n as that is the default 'excel' CSV dialect for line terminator.
    # f.write('A,B,C,D,E,F,G,H,I,J,K\r\n')
    # w.writerow(dict(zip(w.fieldnames,'col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 col11'.split())))
    w.writerows(d['results'])

输出:

sedol,company,name,unitType,perf48t60m,perf36t48m,perf24t36m,perf12t24m,perf12m,initialCharge,netAnnualCharge
B7BW9Y0,BlackRock,BlackRock Global European Value (D2 GBP),Accumulation,n/a,11.29%,0.25%,12.97%,19.37%,0.00,1.07
B76VTR5,Vanguard,Vanguard SRI European Stock,Income,22.01%,9.61%,-3.95%,15.38%,19.69%,0.00,0.30

答案 1 :(得分:0)

我认为p是字典

你可以尝试:

for p in d['results']:
    for key in p.keys():
        result = a[i]+',',
print result

您可以尝试使用csv部分:

import csv 
csv_file = open('your_csv.csv', 'wb') 
csv_outp = csv.writer(csv_file, delimiter=',') 
csv_outp.writerow(result)

我希望这可以帮到你