本文介绍了(python)如果列表不为空,则访问JSON上的嵌套值,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问json值,只打印不为空的'tourList'

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

然后我得到了这个错误

我认为该错误是因为某些tourList为空,请帮助我如何检查tourList是否为空,然后仅打印不为空的tourList

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'])是dictslist,而不是dict本身.更改为:

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

或者,如果您只想让所述list中的第一个dict:

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

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

这篇关于(python)如果列表不为空,则访问JSON上的嵌套值,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:23