1

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
  • 1
    B is an object as well as A, you'll need to write response.A["12"] to get "8" Commented Sep 18, 2012 at 12:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

but when i do this var parsedJSON = JSON.parse(xmlHttp.responseText); alert(parsedJSON.A[8]); i get 'undefined' in alert box :(
Use quotes or it will be consider as the eighth element: alert(parsedJSON.A["8"]);
is there a way through which i can store all the keys of the object A and object B in 2 different variables ?
You mean like var a = array.A, b = array.B; ??? Or just the keys? Try for(key in array.A){console.log(array.A[key]);}
I mean i want to store all the keys of object A (namely 12 and 8) in a variable
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:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.