json - 在 python 中解析 Alexa json 响应以获取值名称时出现问题
问题描述
我将以下意图传递给我的处理程序:
"request": {
"type": "IntentRequest",
"requestId": "amzn1.echo-api.request.3af5c8c3-1d1f-4169-8ce8-fde1a99a7c8d",
"timestamp": "2019-04-03T04:08:06Z",
"locale": "en-US",
"intent": {
"name": "get_speeds",
"confirmationStatus": "NONE",
"slots": {
"direction": {
"name": "direction",
"value": "inbound",
"resolutions": {
"resolutionsPerAuthority": [
{
"authority": "amzn1.er-authority.echo-sdk.amzn1.ask.skill.e76bf13b-71ac-4a90-94d4-597aa597ae87.direction",
"status": {
"code": "ER_SUCCESS_MATCH"
},
"values": [
{
"value": {
"name": "inbound",
"id": "a8e6fe5b9e68f30a146cefebaa7edcc3"
}
}
]
}
]
},
"confirmationStatus": "NONE",
"source": "USER"
}
}
},
"dialogState": "COMPLETED"
}
我想提取实际值,而不是话语,例如值名称,在本例中为“入站”。我已经尝试过这个和各种类似的迭代(打印用于调试):
slots = handler_input.request_envelope.request.intent.slots
resolutions = slots["direction"].resolutions
print(resolutions)
print(resolutions["resolutions_per_authority"])
direction = resolutions["resolutions_per_authority"][0]["values"][0]["value"]["name"]
session_attr = handler_input.attributes_manager.session_attributes
我也尝试过与“resolutionsPerAuthority”相同的方法,它是传递的 JSON,但显然不是我的程序输出的结果,因为日志有:
04:08:07
{'resolutions_per_authority': [{'authority': 'amzn1.er-authority.echo-sdk.amzn1.ask.skill.e76bf13b-71ac-4a90-94d4-597aa597ae87.direction',
04:08:07
'status': {'code': 'ER_SUCCESS_MATCH'},
04:08:07
'values': [{'value': {'id': 'a8e6fe5b9e68f30a146cefebaa7edcc3',
04:08:07
'name': 'inbound'}}]}]}
04:08:07
'Resolutions' object is not subscriptable
这是我在所有方法中不断遇到的错误:“解决方案”对象不可下标。有人可以帮助我如何提取规范槽值吗?我需要为其他几个意图做同样的事情,但我认为如果我能让这个工作正常,它将成为其他意图的模型。
解决方案
好的,我终于找到了一个使用相对较新SDK的面向对象版本的python示例,就像我一样。该示例是 Amazon 的PetMatch示例的 python 版本。
基于此,以下工作:
slots = handler_input.request_envelope.request.intent.slots
direction = slots["direction"].resolutions.resolutions_per_authority[0].values[0].value.name
我仍然希望更好地了解它是如何工作的,但至少它正在工作,并且还可以帮助其他人。我发现对于 Alexa 示例和文档,有很多内容,但组织得不好,而且 api 不断变化,所以你发现的一些内容已经过时了。
推荐阅读
- aws-lambda - AWS SDK - Invoke Lambda function no response on success
- google-apps-script - Google Apps 脚本:API 错误消息“client_id is required”
- python - How to get the logged in user ip and compare it with the previous ip, if the ip address is different, a message is issued (Django)
- swift - TableView Swipe Action Button change after clicked
- flutter - Drag and drop inside expansion tile?
- angular - 使用 Angular 9 无法正确加载数据表分页、搜索和排序
- html - Quasar Layout Two Column scrollbars
- c++ - 结构元组/在结构中包装一组可变参数模板参数值
- python - 使用python删除文件夹中的所有pdf文件
- algorithm - 在给定矩阵中查找最大模式