I am trying to execute below code but it's throwing some error, whereas same code is running on jupyter notebook. I am not sure what's going wrong. The python version is 2 on both platform. This codes takes json file as input, pick 'Data' key and place all values under it into csv file.
command line :
Python version : 2.6.6
$ python Parser.py /data/csdb/stage/fundapiresponse.json /data/csp53/csdb/stage/fundresponse.csv
File "Parser.py", line 27
flat_data = [{k:v for j in i for k, v in j.items()} for i in zip(*[element['Data'] for key in element])]
^
SyntaxError: invalid syntax
Code:
#################################################
# importing libraries
#################################################
import csv
import json
import collections
import sys
#################################################
# Reading input and output file from command line
#################################################
infile = sys.argv[1]
outfile = sys.argv[2]
print infile
print outfile
#################################################
# Read JSON and build CSV layout
#################################################
with open(infile,'r') as f:
data= json.load(f)
with open(outfile, 'w') as f:
for element in data:
flat_data = [{k:v for j in i for k, v in j.items()} for i in zip(*[element['Data'] for key in element])]
csvwriter = DictWriter(f,flat_data[0].keys(),lineterminator='\n')
csvwriter.writerows(flat_data)
Jupyter notebook :
Python 2
#################################################
# importing libraries
#################################################
import csv
import json
import collections
import sys
#################################################
# Reading input and output file from command line
#################################################
infile = 'fundapiresponse.json'
outfile = 'fundresponse.csv'
print infile
print outfile
#################################################
# Read JSON and build CSV layout
#################################################
with open(infile,'r') as f:
data= json.load(f)
with open(outfile, 'w') as f:
for element in data:
flat_data = [{k:v for j in i for k, v in j.items()} for i in zip(*[element['Data'] for key in element])]
csvwriter = DictWriter(f,flat_data[0].keys(),lineterminator='\n')
csvwriter.writerows(flat_data)