我知道这个问题已经被问了很多次了.但是我不知道会发生什么,我在尝试解析json响应时遇到了问题。这是json (摘录)
{"result":{"fulfillment":{"speech":"[{\"name\":\"Pallet truck\",\"object_type\":\"machine\",\"object_id\":3279}, ... 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
},发布于 2017-12-08 10:39:11
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}]}}}');。
https://stackoverflow.com/questions/47706856
复制相似问题