JSON.parse使用嵌套对象解析JSON [英] JSON.parse parsing JSON with nested objects
问题描述
我正在尝试使用在post请求的响应中收到的嵌套对象来解析JSON字符串。运行 JSON.parse(responseText)
后,结果如下:
I'm attempting to parse a JSON string with nested objects received in the response of a post request. After running JSON.parse(responseText)
, the result is in the following format:
[{
"atco":"43000156407",
"location":{
"longitude":"-1.7876500000000000",
"latitude":"52.4147200000000000","
timestamp":"2013-03-19 11:30:00"
},
"name":"Solihull Station Interchange",
"road":"STATION APPROACH",
"direction":"NA",
"locality":"Solihull",
"town":"Solihull"}, ...
我认为我可以使用以下内容作为示例拉出值,但我得到的都是未定义的。
I thought I would then be able pull values out using the following as an example, but all I get is undefined.
var atco = json[0].atco;
我也试过 json [0] [0]
但是返回JSON中的单个字符( [
)。这是否表明JSON没有正确解析,或者这是预期的行为,我只是错误地引用?
I've also tried json[0][0]
but that returns an individual character from the JSON ([
) . Does this indicate the JSON hasn't parsed correctly, or is this expected behaviour and I'm just referencing incorrectly?
推荐答案
这意味着您的JSON正在进行双重编码。确保你只在服务器上对其进行一次编码。
This means that your JSON is being double encoded. Make sure you only encode it once on the server.
作为证明,在你解析它之后,再次解析它。
As proof, after you've parsed it, parse it again.
var parsed = JSON.parse(resposneText);
var parsed2 = JSON.parse(parsed);
alert(parsed2.atco);
要不然,或者你正在解析但是然后尝试从原始字符串中选择数据。这显然不起作用。
Either that, or you're parsing it but then trying to select the data from the original string. This would obviously not work.
这篇关于JSON.parse使用嵌套对象解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!