Skip to content

Instantly share code, notes, and snippets.

@sugavaneshb
Created October 10, 2014 06:32
Show Gist options
  • Save sugavaneshb/eb52df3678c2b35da133 to your computer and use it in GitHub Desktop.
Save sugavaneshb/eb52df3678c2b35da133 to your computer and use it in GitHub Desktop.
A simple JSON to CSV file converter
import os
import sys
import csv
import codecs
import json
reload(sys)
sys.setdefaultencoding('utf-8')
'''
Determine the different keys present in JSON
'''
def get_keys(data):
keys = set()
for k in data:
for obj in data[k]:
keys.add(obj)
return keys
'''
Convert JSON to CSV:
1. Identify the keys in JSON
2. Pretty print CSV file
'''
def do_conversion(sep):
print('I am in do_conversion')
file_name = 'test.json'
with codecs.open(file_name, 'r', encoding='utf-8') as data_file:
data = json.load(data_file)
keys = get_keys(data)
print 'jsonKey' + sep + sep.join(keys)
for k in data:
csvLine = []
csvLine.append(k)
for key in keys:
if(key in data[k]):
csvLine.append(data[k][key])
else:
csvLine.append('')
csvString = sep.join(csvLine)
print csvString + os.linesep
do_conversion(';')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment