如何在javascript中通过json解析关联数组

时间:2021-12-21 01:17:17

I have a 2-D php array which i am encoding through JSON. My 2d array in php is something like this:

我有一个用JSON编码的二维php数组。php中的二维数组是这样的:

$array['A'][12] = 8;
$array['A'][8] = 21;

$array['B'][17] = 19;
$array['B'][9] = 12;

when I do echo json_encode($array); and alert this as Ajax xmlhttp.responsetext i get this in my alert box : {"A":{"12":"8","8":"21"},"B":{"17":"19","9":"12"}}

当我回显json_encode($array)时;并将其警告为Ajax xmlhttp。responsetext我得到这个警告框:{ " A ":{“12”:“8”,“8”:“21”},“B”:{“17”:“19”,“9”:" 12 " } }

which is absolutely fine. Now i need to parse it in javascript so i used the JSON.parse() function. The problem is when i access the A and B fields of the string. I get this in my alert boxes: Object object. How to parse this associative array? I am a beginner in AJAX and JSON so please help.

这是非常好的方式。现在我需要在javascript中解析它,所以我使用了JSON.parse()函数。问题是当我访问字符串的A和B字段时。在我的警告框:Object对象中。如何解析这个关联数组?我是AJAX和JSON的初学者,所以请帮忙。

2 个解决方案

#1


3  

var array = JSON.parse(yourResponseData);

array.A // Object
array.A['12'] //8

You can't access the key '12' via the dot syntax becase no variable name can start with a number.

不能通过点语法访问键'12',因为任何变量名都不能以数字开头。

#2


0  

You can use console.log() rather than alert() to see the complete structure of that parsed json object. You can easily retrieve the value by using . notation or [] brackets: For example:

您可以使用console.log()而不是alert()来查看解析后的json对象的完整结构。您可以通过使用轻松检索值。符号或[]括号:例如:

var returned = JSON.parse(tran.responseText);
console.log(returned['A']['8']); //which should give you '21' based on your case

#1


3  

var array = JSON.parse(yourResponseData);

array.A // Object
array.A['12'] //8

You can't access the key '12' via the dot syntax becase no variable name can start with a number.

不能通过点语法访问键'12',因为任何变量名都不能以数字开头。

#2


0  

You can use console.log() rather than alert() to see the complete structure of that parsed json object. You can easily retrieve the value by using . notation or [] brackets: For example:

您可以使用console.log()而不是alert()来查看解析后的json对象的完整结构。您可以通过使用轻松检索值。符号或[]括号:例如:

var returned = JSON.parse(tran.responseText);
console.log(returned['A']['8']); //which should give you '21' based on your case