I am trying to convert a nested JSON object file into CSV. Here is the sample of JSON
{
"total_hosts" : [
{
"TYPE" : "AGENT",
"COUNT" : 6
}
],
"installed" : [
{
"ID" : "admin-4.0",
"VERSION" : 4,
"ADDON_NAME" : "Administration"
},
{
"ID" : "admin-2.0",
"VERSION" : 2,
"ADDON_NAME" : "Administration"
},
{
"ID" : "ch-5.0",
"VERSION" : "5",
"ADDON_NAME" : "Control Host"
}
],
"virtual_machine" : [
{
"COUNT" : 4,
"TYPE" : "VM"
}
TYPE,COUNT,ID,VERSION like these are columns but the problem is not each object have values in it some have 1 object with these values or some have more so,I write in row , so i am trying to write blank space when there is no value for that column.
the code to write it into CSV
json_input = open('all.json')
try:
decoded = json.load(json_input)
# tell computer where to put CSV
outfile_path='Path to CSV'
# open it up, the w means we will write to it
writer = csv.writer(open(outfile_path,'w'))
for index in range(len(decoded['installed'])):
row = []
if decoded['total_hosts'][index]['TYPE'] is None:
row.append(str(''))
else:
row.append(str(decoded['total_hosts'][index]['TYPE']))
if decoded['total_hosts'][index]['COUNT'] is None:
row.append(str(''))
else:
row.append(str(decoded['total_hosts'][index]['COUNT']))
writer.writerow(row)
I am getting Index out of range error , I even tried True/False condition for if.
Can anyone help me with this?
Updated : Expected Output :
TYPE,COUNT,ID,VERSION,ADDON_NAME,COUNT,TYPE
AGENT,6,admin-4.0,4,Administration,4,VM
, ,admin-2.0,2,Administration, ,
, ,cd-5.0,5,Control Host, ,
So basically i need blank spaces when there is no value for that column.
Quesion Modified : OUTPUT :
AGENT,6,,,
, ,admin-4.0,4,Administration
, ,admin-2.0,2,Administration
, ,ch-5.0,5,Control Host
Expected OUTPUT :
AGENT,6,admin-4.0,4,Administration
, ,admin-2.0,2,Administration
, ,ch-5.0,5,Control Host
Updated : I even tried
row.append(str(entry.get('TYPE', '')))
row.append(str(entry.get('COUNT', '')))
row.append(str(entry.get('ID', '')))
row.append(str(entry.get('VERSION', '')))
row.append(str(entry.get('ADDON_NAME', '')))
writer.writerow(row)
Still got the same output as above. :(
installed, andtotal_hostslists don't have the same length; you are looping overrange(len(decoded['installed']))but then use the index in thedecoded['total_hosts']anddecoded['_hosts']lists (the latter is probably a typo).decoded['total_hosts'][index]operation that throws the exception, no trying to access['TYPE'](which would throw aKeyErrorexception instead).