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

自闭症网瘾萝莉.ら 提交于 2019-12-11 16:33:32

问题


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"

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/48181747/python-accessing-nested-value-on-json-if-list-not-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!