如何遍历API返回的JSON数据?Python代码调试求助
遍历API返回的所有家具数据
修正后的代码
你需要遍历API返回的data数组本身,而非数组内单个元素的字段。以下是可正确遍历所有数据的代码:
import requests swf = input("write: ") # 发送请求并解析JSON数据 response = requests.get(f"https://apihabbo.com/api/furnis?hotel=es&name={swf}") data_list = response.json()["data"] # 遍历每个家具条目 for furni in data_list: # 按需提取字段,比如name和code print(f"家具名称: {furni['name']}, 编码: {furni['code']}")
错误原因分析
你之前的尝试存在两个核心问题:
- 初始代码仅取
data[0],只获取了数组的第一个元素,因此只能拿到单条数据。 - 错误尝试中
for i in data['data'][0]['code']是在遍历单个家具的code字符串(逐个字符遍历),而非整个data数组,自然无法输出所有家具数据。
更健壮的版本(处理异常情况)
为避免API返回结构变化或无数据导致的报错,可加入容错处理:
import requests swf = input("write: ") response = requests.get(f"https://apihabbo.com/api/furnis?hotel=es&name={swf}") # 用get方法获取data,默认返回空列表防止键不存在报错 data_list = response.json().get("data", []) if not data_list: print("未查询到相关家具数据") else: for furni in data_list: # 用get方法获取字段,避免字段缺失报错 name = furni.get("name", "未知名称") code = furni.get("code", "未知编码") print(f"名称: {name}, 编码: {code}")
内容的提问来源于stack exchange,提问作者Albinha
相关产品推荐
相关产品推荐

