Skip to content

Instantly share code, notes, and snippets.

@ffr4nz
Last active March 12, 2017 16:17
Show Gist options
  • Save ffr4nz/1866d2bc8c5befbefb34ab37cf4b0d50 to your computer and use it in GitHub Desktop.
Save ffr4nz/1866d2bc8c5befbefb34ab37cf4b0d50 to your computer and use it in GitHub Desktop.
Create CSV row using CSV library from JSON Object using StringIO
import csv
import json
import StringIO
'''
Create CSV row using CSV library from JSON Object using StringIO
'''
json_doc = '{"key1":"value1","key2":"value2","key3":"value3"}' # JSON Document as Text
csv_doc_field = ['key1','key2'] # Field to be processed
csv_doc = StringIO.StringIO() # 'False' file to use with CSV Writer
json_doc = json.loads(json_doc) # Create JSON Object
output = csv.writer(csv_doc) # Create CSV writer using StringIO file
tt = list() # Field list
for field in csv_doc_field: # Loop each field
tt.append(json_doc[field]) # Append each value processed
output.writerow(tt) # Write row into StringIO file
print csv_doc.getvalue() # Show result -> value1,value2
csv_doc.close() # Close StringIO file
@javimoral
Copy link

Ahórrate el for con list comprehension :)
output.writerow([x[1] for x in json_doc.iteritems() if x[0] in csv_doc_field])

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