0

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"
2
  • details = item['tourList'][0] to get the dictionary before you try to access the key Commented Jan 10, 2018 at 6:53
  • Your details is referencing a list of ` tourList, that's why your details[key]` is failing because it's expecting the index of a list, not the key of a dictionary as you expected. Edit: what Krishna said. Commented Jan 10, 2018 at 6:56

2 Answers 2

3

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))
Sign up to request clarification or add additional context in comments.

2 Comments

done, thanks :) 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"
That's a new question ;) you have to find a way to get down the nesting levels.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.