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] ?

share|improve this question

9% accept rate
feedback

3 Answers

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.

share|improve this answer
feedback

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.

share|improve this answer
feedback

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]);
share|improve this answer
Unless my eyes deceive me, the only difference there is you've renamed parent1[] to parent1 and parent2[] to parent2. How would this fix the code? :/ The 'parents' are the names of inputs within my HTML form. The inputs are arrays and, therefor, are named with []. – dave Jun 17 '10 at 4:24
OK, so you don't have to rename as I did. But you can still access them as: for (var i = 0; i < data['parent1[]'].length; i++) { alert( data['parent1[]'][i]); } – Khnle Jun 17 '10 at 4:38
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.