如何将这个json代码写入csv文件?

时间:2016-12-11 18:37:00

标签: python json csv

我从未使用过json而我只是一个python用户,你如何将这个json格式写入csv文件:

{
    "meta": {},
    "data": {
        "suggestionTitleAccessor": "symbol",
        "items": [
            {
                "name": "Automatic Data Processing, Inc.",
                "exch": "NMS",
                "type": "S",
                "symbol": "ADP",
                "exchDisp": "NASDAQ",
                "typeDisp": "Equity"
            },
            {
                "name": "Adeptus Health Inc.",
                "exch": "NYQ",
                "type": "S",
                "symbol": "ADPT",
                "exchDisp": "NYSE",
                "typeDisp": "Equity"
            },
            {
                "name": "ADP170217P00080000",
                "exch": "OPR",
                "type": "O",
                "symbol": "ADP170217P00080000",
                "exchDisp": "OPR",
                "typeDisp": "Option"
            },
            {
                "name": "Automatic Data Processing, Inc.",
                "exch": "FRA",
                "type": "S",
                "symbol": "ADP.F",
                "exchDisp": "Frankfurt",
                "typeDisp": "Equity"
            },
            {
                "name": "Adelphia Recovery Trust",
                "exch": "PNK",
                "type": "S",
                "symbol": "ADPAJ",
                "exchDisp": "OTC Markets",
                "typeDisp": "Equity"
            },
            {
                "name": "Adelphia Recovery Trust",
                "exch": "PNK",
                "type": "S",
                "symbol": "ADPAS",
                "exchDisp": "OTC Markets",
                "typeDisp": "Equity"
            },
            {
                "name": "AB Short Duration A",
                "exch": "NAS",
                "type": "M",
                "symbol": "ADPAX",
                "exchDisp": "NASDAQ",
                "typeDisp": "Fund"
            },
            {
                "name": "AB Short Duration B",
                "exch": "NAS",
                "type": "M",
                "symbol": "ADPBX",
                "exchDisp": "NASDAQ",
                "typeDisp": "Fund"
            },
            {
                "name": "AB Short Duration C",
                "exch": "NAS",
                "type": "M",
                "symbol": "ADPCX",
                "exchDisp": "NASDAQ",
                "typeDisp": "Fund"
            },
            {
                "name": "A\u00c3\u00a9roports de Paris S.A.",
                "exch": "PAR",
                "type": "S",
                "symbol": "ADP.PA",
                "exchDisp": "Paris",
                "typeDisp": "Equity"
            }
        ],
        "suggestionMeta": [
            "symbol",
            "name",
            "exch",
            "type",
            "exchDisp",
            "typeDisp"
        ],
        "hiConf": false
    }
}

我试过

import json
import csv
body = {"data":{"suggestionTitleAccessor":"symbol","suggestionMeta":["symbol","name","exch","type","exchDisp","typeDisp"],"hiConf":false,"items":[{"symbol":"ADP","name":"Automatic Data Processing, Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"ADPT","name":"Adeptus Health Inc.","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"ADP170217P00080000","name":"ADP170217P00080000","exch":"OPR","type":"O","exchDisp":"OPR","typeDisp":"Option"},{"symbol":"ADP.F","name":"Automatic Data Processing, Inc.","exch":"FRA","type":"S","exchDisp":"Frankfurt","typeDisp":"Equity"},{"symbol":"ADPAJ","name":"Adelphia Recovery Trust","exch":"PNK","type":"S","exchDisp":"OTC Markets","typeDisp":"Equity"},{"symbol":"ADPAS","name":"Adelphia Recovery Trust","exch":"PNK","type":"S","exchDisp":"OTC Markets","typeDisp":"Equity"},{"symbol":"ADPAX","name":"AB Short Duration A","exch":"NAS","type":"M","exchDisp":"NASDAQ","typeDisp":"Fund"},{"symbol":"ADPBX","name":"AB Short Duration B","exch":"NAS","type":"M","exchDisp":"NASDAQ","typeDisp":"Fund"},{"symbol":"ADPCX","name":"AB Short Duration C","exch":"NAS","type":"M","exchDisp":"NASDAQ","typeDisp":"Fund"},{"symbol":"ADP.PA","name":"Aéroports de Paris S.A.","exch":"PAR","type":"S","exchDisp":"Paris","typeDisp":"Equity"}]},"meta":{}}
x = json.loads(body)
f = csv.writer(open("test.csv", "wb+"))
for x in x:
    csvwriter.writerow(x())
    f.close()

但它产生一个空的test.csv文件。我认为这是由于行csvwriter.writerow(x())x是一个数组而且我没有正确地编写单元格。

编辑:我正在寻找的输出类型基本上是一个csv数组,每个项目都是行,所以:

Adeptus Health Inc.,NYQ,S,ADPT,NYSE,Equity
ADP170217P00080000,OPR,O,ADP170217P00080000,OPR,Option
etc

3 个答案:

答案 0 :(得分:2)

在您的情况下,DictWriter会有所帮助。

小例子:

import csv

body = [
    {'name': 'A', 'value1': 1, 'value2': 2},
    {'name': 'B', 'value1': 1, 'value2': 2}
]

with open('items.csv', 'w') as csvfile:
    fieldnames = ['name', 'value1', 'value2']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for item in body:
        writer.writerow(item)

答案 1 :(得分:1)

如果您只需要'项目',您可能会出现以下情况。 if i == 0:只是写一个标题。

#coding: utf-8
import json
import csv

body = "..."
x = json.loads(body)

with open('test.csv', 'w', newline='') as csvfile:
  wHandle = csv.writer(csvfile)
  for i, item in enumerate(x['data']['items']):
    if i == 0:
      wHandle.writerow(item.keys())
    wHandle.writerow(item.values())

答案 2 :(得分:0)

我尝试了以下代码,我在文件中使用了JSON

import csv
import json

json_file='your.json'
with open(json_file, 'r') as json_data:
    x = json.load(json_data)

f = csv.writer(open("test.csv", "w"))#store result in test.csv

#store header name in variable, later w.r.t value from variable will retrieve respective data 
symbol=x['data']['suggestionMeta'][0]
name=x['data']['suggestionMeta'][1]
exch=x['data']['suggestionMeta'][2]
dtype=x['data']['suggestionMeta'][3]
exchdisp=x['data']['suggestionMeta'][4]
typedisp=x['data']['suggestionMeta'][5]
# Write CSV Header, If you dont need that, remove this line
f.writerow([symbol,name,exch,dtype,exchdisp,typedisp])
for key in x['data']['items']:
    f.writerow([key[symbol],key[name],key[exch],key[dtype],key[exchdisp],key[typedisp]])

<强>输出

symbol,name,exch,type,exchDisp,typeDisp
ADP,"Automatic Data Processing, Inc.",NMS,S,NASDAQ,Equity
ADPT,Adeptus Health Inc.,NYQ,S,NYSE,Equity
ADP170217P00080000,ADP170217P00080000,OPR,O,OPR,Option
ADP.F,"Automatic Data Processing, Inc.",FRA,S,Frankfurt,Equity
ADPAJ,Adelphia Recovery Trust,PNK,S,OTC Markets,Equity
ADPAS,Adelphia Recovery Trust,PNK,S,OTC Markets,Equity
ADPAX,AB Short Duration A,NAS,M,NASDAQ,Fund
ADPBX,AB Short Duration B,NAS,M,NASDAQ,Fund
ADPCX,AB Short Duration C,NAS,M,NASDAQ,Fund
ADP.PA,Aéroports de Paris S.A.,PAR,S,Paris,Equity

希望这有助于你