本文介绍在 Python 中解析 Yelp 等来源的 JSON 数据时,如何同时解决 HTML 实体(如 ')和乱码 Unicode 问题,推荐使用 response.json() 自动解码 + html.unescape() 清洗字段的组合方案。
本文介绍在 python 中解析 yelp 等来源的 json 数据时,如何同时解决 html 实体(如 `'`)和乱码 unicode 问题,推荐使用 `response.json()` 自动解码 + `html.unescape()` 清洗字段的组合方案。
在调用外部 API(例如 Yelp 商户评论接口)获取 JSON 响应时,常遇到两类编码干扰:一是原始数据中混入了 HTML 实体编码(如 ' 表示单引号 '," 表示双引号 "),二是响应未正确声明字符集,导致 response.text 解析为错误的字符串(如 u'u00e9' 显示为 é 的乱码形式)。若直接使用 json.loads(response.text, strict=False),虽能绕过部分 JSON 语法限制,但无法自动还原 HTML 实体,也无法保障 Unicode 解码准确性。
推荐做法是分两步处理:
✅ 示例代码:
import htmlimport requestsdef parse_yelp_restaurant_api(self, response): # 步骤1:使用 response.json() 自动解码并解析 JSON jsonresponse = response.json() # ✅ 比 json.loads(response.text) 更可靠 # 步骤2:遍历需清洗的文本字段(如 review.text、business.name) for review in jsonresponse.get("reviews", []): if "text" in review: review["text"] = html.unescape(review["text"]) # ✅ 安全还原 HTML 实体 if "excerpt" in review: review["excerpt"] = html.unescape(review["excerpt"]) return jsonresponse
⚠️ 注意事项:
立即学习“前端免费学习笔记(深入)”;
综上,response.json() + html.unescape() 是兼顾健壮性与简洁性的最佳实践,既规避了手动编码推断的陷阱,又精准清理了 HTML 转义污染,适用于 Yelp、Google Places 等常见含 HTML 实体的 API 数据源。