(蟒蛇)在JSON访问嵌套的值,如果列表不为空,((python) Accessing nested

2019-10-30 06:29发布

我试着去访问JSON值,而只打印“tourList”这不是空

import json
json_obj = {
"STATUS": "SUCCESS",
"DATA": {
    "data": [
        {
            "destinationId": "36",
            "name": "Bali ",
            "destinationCode": "DPS",
            "tourList": []
        },
        {
            "destinationId": "216",
            "name": "Bandung",
            "destinationCode": "24417",
            "tourList": []
        },
        {
            "destinationId": "54",
            "name": "Batam",
            "destinationCode": "BTH",
            "tourList": [
                {
                    "tourId": "20586",
                    "tourCode": "IDBTH00585",
                    "tourName": "BATAM SPECIAL SPA PACKAGE",           
                    "tourTime": [
                        {
                            "tourStartTime": "09:00:00",
                            "tourEndTime": "16:00:00",

                        }
                    ],
                    "pricing": [
                        {
                            "adultPrice": "193.00",
                            "tourId": "20586"
                        }
                    ]
                }
            ]
        }          

    ]
 }
}

wanted = ['tourId', 'tourCode', 'tourName', 'tourTime','pricing']

for item in json_obj["DATA"]["data"]:
    details = item['tourList']
    if not details:
       print("")
    else:
        for key in wanted:
            print(key, ':', json.dumps(details[key], indent=4))
            #Put a blank line at the end of the details for each item
            print() 

然后我得到这个错误

回溯(最后最近一次调用):文件“testapi.py” 57行,在打印(键,“:”,json.dumps(细节[关键],缩进= 4))类型错误:列表索引必须为整数或切片,不str的

即时通讯思想的错误,因为一些tourList是空的,帮我如何检查tourList是空的,然后只打印tourList不是空

也可以帮我,这样的结果是这样的

tourId : "20586"
tourCode : "IDBTH00585"
tourName : "BATAM SPECIAL SPA PACKAGE"
tourStartTime: "09:00:00"
tourEndTime: "16:00:00"
adultPrice: "193.00"
tourId: "20586"

Answer 1:

detailsitem['tourList']listdicts ,而不是一个dict本身。 改成:

for d in details:
    for key in wanted:
        print(key, ':', json.dumps(d[key], indent=4))

或者,如果你只想要第一个dict中说list

for key in wanted:
    print(key, ':', json.dumps(details[0][key], indent=4))


Answer 2:

希望它可以帮助你:

data = json_obj.get("DATA")
for key in data.keys():
    for get_list in data[key]:
        if not get_list.get('tourList'):
            print('Skip it')         
        else:
            print('Do Something')


文章来源: (python) Accessing nested value on JSON if list not empty,