从PHP获取JSON时遇到问题。下面的代码是有效的:
[{
"vehicleId": "1",
"status": "Running",
"position": "x",
"battery": "25",
"distanceTravelled": "123",
"destination": "y",
"freeSeats": "2",
"speed": "32"
}
]
但是,我的新版本的代码就是这样(数字值中没有引号),它给出了一个解析Json错误,它没有显示任何内容。
[{
"vehicleId": 1,
"status": "Running",
"position": "x",
"battery": 25,
"distanceTravelled": 123,
"destination": "y",
"freeSeats": 2,
"speed": 32
}
]
我在jsonlint.com检查了格式,它是有效的。 Eclipse中的日志错误是:
05-09 21:37:25.536: E/Web Console(336): SyntaxError: Unable to parse JSON string at file:///android_asset/www/MobileMan.js:37
34 xmlhttp.open("GET",url,false);
35 xmlhttp.send();
36 var json = xmlhttp.responseText;
37 obj = JSON.parse(json);
我还在Chrome上的计算机上尝试了Javascript代码,一切正常。我无法解决问题。谢谢你的回答。
答案 0 :(得分:0)
如果解析器抛出错误,那么它意味着提供给parse的值不是纯JSON对象。
另一方面,关于JSON.stringify
因此,在您的情况下,您首先需要将获得的结果转换为JSON对象,然后尝试解析它。
a = [{
"vehicleId": 1,
"status": "Running",
"position": "x",
"battery": 25,
"distanceTravelled": 123,
"destination": "y",
"freeSeats": 2,
"speed": 32
}
];
var b = JSON.stringify(a);
var c = JSON.parse(b);
console.log(c)