[英]Can't parse DialogFlow json response
我知道這個問題已經被問過多次了……但是當我試圖解析一個json響應時,我不知道發生了什么問題。 這是json(摘錄)
{"result":{"fulfillment":{"speech":"[{\"name\":\"Pallet truck\",\"object_type\":\"machine\",\"object_id\":3279}, ...
我正在像這樣應用JSON解析
var obj = JSON.parse(response);
然后我有這樣的東西
"result":{
"fulfillment":{
"speech":"[
{"name":"Pallet truck","object_type":"machine","object_id":3279},
{"name":"CollaborativeRobot","object_type":"machine","object_id":3273},
{"name":"Bender","object_type":"machine","object_id":3997},...
我只想在最后顯示這樣:
Name : Pallet Truck
Name : CollaborativeRobot
Name : Bender
我已經嘗試過這樣的事情
for (var key in obj.result.fulfillment.speech) {
if (obj.result.fulfillment.speech.hasOwnProperty(key)) {
console.log(obj.result.fulfillment.speech[key].name.val());
}
}
但是我只有未定義的結果...我想我在訪問數組時丟失了一些東西(已經有一段時間沒有在php / js中進行任何編碼了)
編輯
編輯2
它表明問題出在服務器端,而此處的雙重編碼是摘錄:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.mephisto.optimdata.io/search?object_type=machine');
curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'authorization: JWT '.$accessToken));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$fulfillment = new stdClass();
$fulfillment->speech = $result;
$result = new stdClass();
$result->fulfillment = $fulfillment;
$result->requete = "machines actives";
$responseQueryAPI = new stdClass();
$responseQueryAPI->result = $result;
echo json_encode($responseQueryAPI);
也許這是因為curl響應已經是json了嗎? 卷曲響應如下所示:
[
{
"name": "Pallet truck",
"object_type": "machine",
"object_id": 3279
},
{
"name": "Collaborative Robot",
"object_type": "machine",
"object_id": 3273
},
{
"name": "Bender",
"object_type": "machine",
"object_id": 3997
},
name
只是一個字符串,因此請嘗試替換
for (var key in obj.result.fulfillment.speech) {
if (obj.result.fulfillment.speech.hasOwnProperty(key)) {
console.log(obj.result.fulfillment.speech[key].name.val());
}
}
至
for (var i = 0; i < obj.result.fulfillment.speech.length; ++i) {
console.log(obj.result.fulfillment.speech[i].name);
}
編輯:
響應數據看起來錯誤。
我在JSON.parse('{"result":{"fulfillment":{"speech":"[{\\"name\\":\\"Pallet truck\\",\\"object_type\\":\\"machine\\",\\"object_id\\":3279}]"}}}');
。
嘗試使用JSON.parse('{"result":{"fulfillment":{"speech":[{"name":"Pallet truck","object_type":"machine","object_id":3279}]}}}');
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.