简体   繁体   中英

(python) Accessing nested value on JSON if list not empty,

Im trying to access json value and only print 'tourList' that not empty

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

and then i got this error

Traceback (most recent call last): File "testapi.py", line 57, in print(key, ':', json.dumps(details[key], indent=4)) TypeError: list indices must be integers or slices, not str

im thinking that error because some of the tourList is empty, help me how to check tourList is empty and then only print tourList that is not empty

also can you help me so that the result is like this

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

details ( item['tourList'] ) is list of dicts , not a dict itself. Change to:

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

Or if you only want the first dict in said list :

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

Hope it may help you:

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

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