JSON to csv string in python

Posted on Updated on

from cStringIO import StringIO
import csv


def json_to_csv(data):
    output = StringIO()
    writer = csv.DictWriter(output, data[0].keys())
    writer.writeheader()
    for row in data:
        writer.writerow(row)
    return output


print (write_csv([{"name": "Dolor", "age": "23"}, {"name": "John Doe", "age": "32"}, {"age": "42", "name": "Lorem Ipsum"}], 'output.csv').getvalue())

# output
# age,name
# 23,Abiral
# 32,Lorem
# 42,asdfasd
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s