AWS Lambda处理GitHub Webhook事件无法读取字典键值问题排查
错误原因
你遇到的报错和单引号无关,核心有两个问题:
event中的body字段本身是字符串类型,不是Python字典,直接用键索引访问字符串会触发string indices must be integers的类型错误- 字符串中的
"是HTML转义后的双引号,需要先做转义还原才能正常解析为JSON结构
正确实现步骤
Python环境下可以按照以下流程获取目标字段:
- 导入
json和html标准库 - 还原
body字段的HTML转义字符 - 将处理后的字符串反序列化为Python字典
- 按层级访问
pull_request下的url值
代码示例
import json import html # Lambda触发入参 event = {'version': 2.0, 'routeKey': 'POST /', 'body': '{"action": "synchronize","number": 1,"pull_request": {"url":"https://myurl.com"}}'} # 处理body字段 body_raw = html.unescape(event['body']) body_payload = json.loads(body_raw) # 获取目标值 pr_url = body_payload['pull_request']['url'] print(pr_url)
内容的提问来源于stack exchange,提问作者Ken J
相关产品推荐
相关产品推荐

