(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 上的嵌套值


基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01