【发布时间】:2017-12-08 02:33:52
【问题描述】:
我知道这个问题已经被问过很多次了......但我不知道会发生什么 我在尝试解析 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 了? curl 响应如下所示:
[
{
"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
},
【问题讨论】:
-
看起来像 JSONception(JSON 中的 JSON .. ),因为转义引号
\"。您可以在speech的值上尝试 JSON.parse。类似var speech = JSON.parse(JSON.parse(responce).result.fulfillment.speech) -
是的,我认为可能是服务器端的错误,我将使用我的 php 代码进行编辑以查看发生了什么
标签: javascript json parsing