(python) Accessing nested value on JSON if list not empty,((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()
然后我得到这个错误
回溯(最近一次调用最后一次):文件testapi.py",第 57 行,在打印(键,':',json.dumps(详细信息[键],缩进=4))类型错误:列表索引必须是整数或切片,而不是 str
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
我认为错误是因为某些 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
你也能帮我弄成这样吗
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']
) 是 list
的dicts
,而不是 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 上的嵌套值,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:(python) 如果列表不为空,则访问 JSON 上的嵌套值


- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01