(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 上的嵌套值
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
