Reputation: 2433
I already read Create nested JSON from csv, but it didn't help in my case.
I would like to create a json from an excel spreadsheet using python. the code below generates a dic then a json, however i would like to revise the code further so that i can get the following json. I have had no luck so far.
Desired outcome:
{"items": { "AMS Upgrade": [ {"Total": "30667"}, {"% Complete to end": "100%"}, {"value claimed": "25799"} ], "BMS works": [ {"Total": "35722"}, {"% Complete to end": "10%"}, {"value claimed": "3572"} ] }}
Current outcome:
{"line items": {"AMS Upgrade": "30667", "BMS Modification": "35722"}}
Current code:
book = xlrd.open_workbook("Example - supporting doc.xls")
first_sheet = book.sheet_by_index(-1)
nested_dict = {}
nested_dict["line items"] = {}
for i in range(21,175):
Line_items = first_sheet.row_slice(rowx=i, start_colx=2, end_colx=8)
if str(Line_items[0].value) and str(Line_items[1].value):
if not Line_items[5].value ==0 :
print str(Line_items[0].value)
print str(Line_items[5].value)
nested_dict["line items"].update({str(Line_items[0].value) : str(Line_items[1].value)})
print nested_dict
print json.dumps(nested_dict)
Upvotes: 0
Views: 1701
Reputation: 2701
book = xlrd.open_workbook("Example - supporting doc.xls")
first_sheet = book.sheet_by_index(-1)
nested_dict = {}
nested_dict["line items"] = {}
col_names = {1: "Total", 2: "% Complete to end", 5: "value claimed"}
for i in range(21,175):
Line_items = first_sheet.row_slice(rowx=i, start_colx=2, end_colx=8)
if str(Line_items[0].value) and str(Line_items[1].value):
if not Line_items[5].value ==0 :
inner_list = []
for j in [1, 2, 5]:
inner_list.append({col_names[j]: Line_items[j].value})
nested_dict["line items"].update({str(Line_items[0].value) : inner_list})
print(nested_dict)
print(json.dumps(nested_dict))
Upvotes: 1