Skip to content

Instantly share code, notes, and snippets.

@d30jeff
Created June 26, 2015 02:16
Show Gist options
  • Save d30jeff/c45174f99bde6f4e6a7f to your computer and use it in GitHub Desktop.
Save d30jeff/c45174f99bde6f4e6a7f to your computer and use it in GitHub Desktop.
csv_data = ""
for x in json_format:
csv_data += str(x['name']) + str(x['flowrate']) + str(x['temperature']) + str(x['power']) + str(x['log_time']) + str(x['created_on'])
@pvanheus
Copy link

This could be done somewhat neater. From the variable names I think you're looking for CSV data, but let's first make a list of strings:

fieldnames = ('name','flowrate','temperate','power','log_time','created_on')
for x in json_format:
    row = [ str(x[fieldname]) for fieldname in fieldnames ]

Then if it is CSV output that you want, you want a CSV writer. This code writes your data to stdout in CSV format:

import csv
import sys

fieldnames = ('name','flowrate','temperate','power','log_time','created_on')
writer = csv.DictWriter(sys.stdout, fieldnames)
for x in json_format:
    writer.writerow(x)

@Bennyelg
Copy link

Great answer

@zsrinivas
Copy link

if you don't hate the builtins;

items = ['name', 'flowrate', 'temperature', 'power', 'log_time', 'created_on']
csv_data = reduce(add, map(lambda x: reduce(add, map(str, map(x.get, items))), json_format))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment