我正在尝试构建从api.ai获取json响应的chatbot。我需要在json响应下面显示消息部分。
{
"id": "ae66f8e4-a047-478a-8108-8b0147610f18",
"timestamp": "2017-09-28T05:02:03.552Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "hi",
"action": "",
"actionIncomplete": false,
"parameters": {},
"contexts": [],
"metadata": {
"intentId": "d2f3c8bd-fc1b-4b6b-9d3d-08b6be93364e",
"webhookUsed": "false",
"webhookForSlotFillingUsed": "false",
"intentName": "greetings"
},
"fulfillment": {
"speech": "Hi.Please enter your query.",
"messages": [
{
"type": 0,
"speech": "Hi.Please enter your query."
}
]
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success"
},
"sessionId": "saurabh"
}
以下是示例代码,但无法从spokenResponse变量中的消息部分获取语音。
function prepareResponse(val) {
var debugJSON = JSON.stringify(val,undefined, 2);
var spokenResponse = val.messages.speech;
respond(spokenResponse);
debugRespond(debugJSON);
}
我得到以下错误:
script.js:33 Uncaught TypeError: Cannot read property 'speech' of undefined
at prepareResponse (script.js:33)
at Object.success (script.js:21)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4)
但是,当我尝试从结果部分获取源时,它会正确获取。
var spokenResponse = val.result.source;
我是ajax和Json的新手,请帮助。
答案 0 :(得分:1)
您必须通过履行属性访问邮件。请注意,消息包含一个对象数组,因此为了获取第一个对象的speech属性,您必须访问第一个索引中的对象。
var spokenResponse = val.fulfillment.messages[0].speech;
如果您想迭代所有消息(假设您有多条消息):
var messageArr = val.fulfillment.messages;
var speechArr = [];
for (var i = 0; i < messageArr.length; i++) {
speechArr.push(messageArr[i].speech);
}
这将为您提供一系列语音消息。