解析 API 响应
41.5 解析 API 响应
requests 请求后 r.json() 等价于 json.loads(r.text)。
先判断 status_code 再解析;键不存在用 .get() 防 KeyError。
模拟 API 数据
# ========================================
# 示例:解析 API JSON
# 说明:loads 模拟接口返回
# ========================================
import json
api_text = '{"code": 0, "data": {"title": "Python教程", "views": 1000}}'
resp = json.loads(api_text)
if resp.get('code') == 0:
print(resp['data']['title'], '浏览量', resp['data']['views'])
else:
print('接口错误')