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.
- 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
2 Answers
Reset to default 3var 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条)