I can not convert a Json format into a csv table

1

I tried to convert a json to csv, I tried it directly with the library csv and also with pandas , but it tells me TypeError .

This is my code:

import urllib2, json
url = "https://www.ncdc.noaa.gov/cdo-web/api/v2/stations"
token = 'CPxuwmGOwFTuTrPxPPWznbfnyHHEpHiZ'
req0 = urllib2.Request(url, headers={"token":token})
req = urllib2.urlopen(req0)
jdata = req.read()

import pandas as pd
import json

def jdata(df):
   features = []
   df.apply(lambda X: features.append( 
           geojson.Feature(geometry=geojson.Point((X["long"], 
                                                X["lat"], 
                                                X["elev"])), 
               properties=dict(name=X["name"], 

   description=unicode(X["description"].decode('utf8'))))
                                )
          , axis=1)
   with open('map.geojson', 'w') as fp:
       geojson.dump(geojson.FeatureCollection(features), fp, sort_keys=True)

col = ["elevation", "mindata", "maxdata", "latitude", "name", 
"datacoverage", 
"id", "elevationUnit", "longitude"]
data = [jdata]

print (col)
print (data)
    
asked by D.Guizar 29.06.2017 в 09:39
source

1 answer

0

I guess you want to save the 'results' field of the JSON in a csv, there are several ways with or without Pandas. I leave you a possibility using simply standard Python and the libraries json and csv :

import csv
import json
import urllib2


url = "https://www.ncdc.noaa.gov/cdo-web/api/v2/stations"
token = 'CPxuwmGOwFTuTrPxPPWznbfnyHHEpHiZ'
req0 = urllib2.Request(url, headers={"token":token})
req = urllib2.urlopen(req0)
data = req.read()

jdata = json.loads(data)['results']
cols = ["elevation", "mindate", "maxdate", "latitude", "name", "datacoverage", "id", "elevationUnit", "longitude"]
with open('results.csv', 'wb') as f:
    writer = csv.DictWriter(f, cols)
    writer.writeheader()
    writer.writerows(jdata)

With this we get the following csv:

    
answered by 29.06.2017 / 12:13
source