admin管理员组文章数量:1430016
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
本文标签: ajaxhow to parse an associative array through json in javascriptStack Overflow
版权声明:本文标题:ajax - how to parse an associative array through json in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745470249a2659715.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论