Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. import csv
  2. import json
  3. import StringIO
  4.  
  5. '''
  6. Create CSV row using CSV library from JSON Object using StringIO
  7. '''
  8.  
  9. json_doc = '{"key1":"value1","key2":"value2","key3":"value3"}' # JSON Document as Text
  10. csv_doc_field = ['key1','key2'] # Field to be processed
  11. csv_doc = StringIO.StringIO() # 'False' file to use with CSV Writer
  12. json_doc = json.loads(json_doc) # Create JSON Object
  13. output = csv.writer(csv_doc) # Create CSV writer using StringIO file
  14.  
  15. tt = list() # Field list
  16. for field in csv_doc_field: # Loop each field
  17. tt.append(json_doc[field]) # Append each value processed
  18.  
  19. output.writerow(tt) # Write row into StringIO file
  20. print csv_doc.getvalue() # Show result -> value1,value2
  21. csv_doc.close() # Close StringIO file
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement