简体   繁体   中英

How to Create a Nested JSON using Python

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)

Excel print out: 在此处输入图片说明

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM