ajax - how to parse an associative array through json in javascript - Stack Overflow

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

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

$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"}}

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.

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

$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"}}

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.

Share Improve this question edited Sep 18, 2012 at 12:33 Mohit Srivastava asked Sep 18, 2012 at 12:03 Mohit SrivastavaMohit Srivastava 1,9291 gold badge13 silver badges18 bronze badges 1
  • 1 B is an object as well as A, you'll need to write response.A["12"] to get "8" – Carlo Moretti Commented Sep 18, 2012 at 12:06
Add a ment  | 

2 Answers 2

Reset to default 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.

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745470249a4629099.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信