views:

35

answers:

3

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

A: 

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]);
Khnle
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 [].
Charles
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
A: 

Hi Charles,

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.

Krishnan
+1  A: 

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.

Dave Ward