Download JSON data and convert it to CSV using Python

c24b picture c24b · Mar 14, 2011 · Viewed 11.5k times · Source

I'm currently using Yahoo Pipes which provides me with a JSON file from an URL.

I would like to be able to fetch it and convert it into a CSV file, and I have no idea where to begin (I'm a complete beginner in Python).

How can I fetch the JSON data from the URL?
How can I transform it to CSV?

Thank you

Answer

Hugh Bothwell picture Hugh Bothwell · Mar 14, 2011
import urllib2
import json
import csv

def getRows(data):
    # ?? this totally depends on what's in your data
    return []

url = "http://www.yahoo.com/something"
data = urllib2.urlopen(url).read()
data = json.loads(data)

fname = "mydata.csv"
with open(fname,'wb') as outf:
    outcsv = csv.writer(outf)
    outcsv.writerows(getRows(data))