javascript JSON.parse 使用嵌套对象解析 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16004603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.parse parsing JSON with nested objects
提问by Dannyboy1430
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:
我正在尝试使用在发布请求的响应中收到的嵌套对象来解析 JSON 字符串。运行后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 ([
) . Does this indicate the JSON hasn't parsed correctly, or is this expected behaviour and I'm just referencing incorrectly?
我也试过,json[0][0]
但它从 JSON ( [
)返回一个单独的字符。这是否表明 JSON 没有正确解析,或者这是预期的行为而我只是引用不正确?
回答by
This means that your JSON is being double encoded. Make sure you only encode it once on the server.
这意味着您的 JSON 被双重编码。确保您只在服务器上对其进行一次编码。
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.
要么,要么您正在解析它,然后尝试从原始字符串中选择数据。这显然行不通。