Quote:
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))







