Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement