如何使用Python打印JSON响应中的多个指定字段值?
代码修改方案
你需要提取的name字段全部嵌套在live数组的每一项的channel对象中,按以下方式修改代码即可实现需求:
import json from urllib.request import urlopen url = "https://api.holotools.app/v1/live" response = urlopen(url) data_json = json.loads(response.read()) # 遍历live数组提取所有name for item in data_json["live"]: print(item["channel"]["name"])
如果需要把所有name存入列表统一使用,可以用列表推导式实现:
name_list = [item["channel"]["name"] for item in data_json["live"]] print(name_list)
异常兼容处理
如果担心接口返回的部分数据存在字段缺失导致报错,可以增加字段存在性判断:
for item in data_json["live"]: channel = item.get("channel") if channel and channel.get("name"): print(channel["name"])
内容的提问来源于stack exchange,提问作者Ryley
相关产品推荐
相关产品推荐

