简体   繁体   English

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

[英]how to parse an associative array through json in javascript

I have a 2-D php array which i am encoding through JSON. 我有一个2-D php数组,我通过JSON编码。 My 2d array in php is something like this: 我在php中的2d数组是这样的:

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

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

when I do echo json_encode($array); 当我做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"}} 并将此警告为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. 现在我需要在javascript中解析它,所以我使用了JSON.parse()函数。 The problem is when i access the A and B fields of the string. 问题是当我访问字符串的A和B字段时。 I get this in my alert boxes: Object object . 我在警报框中得到了这个: Object object How to parse this associative array? 如何解析这个关联数组? I am a beginner in AJAX and JSON so please help. 我是AJAX和JSON的初学者,所以请帮忙。

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',因为没有变量名称可以以数字开头。

You can use console.log() rather than alert() to see the complete structure of that parsed json object. 您可以使用console.log()而不是alert()来查看已解析的json对象的完整结构。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM