无法解析DialogFlow json响应

时间:2017-12-08 02:33:53

标签: javascript json parsing

我知道这个问题已被多次询问......但我无法弄清楚会发生什么 我在尝试解析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中没有编码任何东西已经有一段时间了)

修改

Undefined results

undefined

编辑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);

也许这是因为卷曲响应已经是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
    },

1 个答案:

答案 0 :(得分:0)

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}]}}}');语法错误。

尝试使用 {{1}}。