简体   繁体   English

JSON.parse使用嵌套对象解析JSON

[英]JSON.parse parsing JSON with nested objects

I'm attempting to parse a JSON string with nested objects received in the response of a post request. 我正在尝试使用在post请求的响应中收到的嵌套对象来解析JSON字符串。 After running JSON.parse(responseText) , the result is in the following format: 运行JSON.parse(responseText) ,结果采用以下格式:

[{
  "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;

I've also tried json[0][0] but that returns an individual character from the JSON ( [ ) . 我也尝试了json[0][0]但它返回了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. 这意味着您的JSON正在进行双重编码。 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. 这显然不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM