post #11 of 11
Quote:
Originally Posted by dushan24 View Post

That code reads in a JSON file and prints it just fine, but I need to convert it to a CSV
I'm gonna work on this myself tonight, but if you have an answer ready to go I'd love for you to save me some time smile.gif

For Python, give this page a good read before writing anything. PEP-0305. (PEP stands for Python Enhancement Proposal, in case you were curious).

Pretty much all you need is the csv writer object, a file to write to, an optional dialect, and an iterator. To sum up and give a better example, here is some code:
Code:
import csv
import urllib2
import json

"""Suppose our JSON looks like the following:
{
    "employees": [
        { "firstName":"John" , "lastName":"Doe" }, 
        { "firstName":"Anna" , "lastName":"Smith" }, 
        { "firstName":"Peter" , "lastName":"Jones" }
    ]
}
"""

def main():
    url = 'some URL'
    request = urllib2.urlopen(url)

    # if you don't have a URL request, you can use json.loads(string) instead
    data = json.load(request)
    request.close()
    
    # create the csv writer
    writer = csv.writer(file('somefile.csv', 'w'))

    # loop through the employees and write to the file
    for emloyee in data['employees']:
        first = employee['firstName']
        last = employee['lastName']
        writer.writerow('%s %s' % (first, last))