Reputation: 7857
I'm using PHP to return a json_encode()'d array for use in my Javascript code. It's being returned as:
{"parent1[]":["child1","child2","child2"],"parent2[]":["child1"]}
By using the following code, I am able to access parent2 > child1
$.getJSON('myfile.php', function(data)
{
for (var key in data)
{
alert(data[key]);
}
}
However, this doesn't give me access to child1, child2, child
, of parent1
. Alerting the key by itself shows 'parent1' but when I try to alert it's contents, I get undefined.
I figured it would give me an object/array? How do I access the children of parent1?
data[key][0] ?
Upvotes: 0
Views: 7549
Reputation: 60580
You're only iterating one level into the object, so it's correct that you're only seeing the parents. You'll need to descend into those keys to find the children.
// Generally, avoid the "foreach" form in JavaScript.
for (var i = 0; i < data.length; i++) {
alert(data[i]); // Parent1[], Parent2[], etc
var parent = data[i];
for (var j = 0; j < parent.length; j++) {
alert(parent[j]); // Child1, Child2, etc
}
}
Aside, the [] suffix on Parent keys is okay. It is valid JSON.
Upvotes: 1
Reputation: 12201
you can assign it in a variable as follows:
var = data[key];
and then get the contents of the array by using the size of the array.
Hope that helps.
Upvotes: 0
Reputation: 10857
The JSON returned should be:
{"parent1":["child1","child2","child2"],"parent2":["child1"]}
then you can access them as:
var data = {"parent1":["child1","child2","child2"],"parent2":["child1"]}
alert(data['parent1'][0]);
alert(data['parent1'][1]);
alert(data['parent1'][2]);
Upvotes: 1