Access JSON array values?

Go To StackoverFlow.com

-1

eSo I've got some parsed php data whiched I've fetched from my database and then parsed to JSON with json_encode(). Then I've used JSONparse() to make objects of my array. My code looks like this:

$.get("fetchDatabase.php", function(data){
var parsedData = jQuery.parseJSON(data); }

I'm left with the array parsedData which looks like this:

[

{"person0":{"name":["Erik Steen"],"age":["1"]}},
{"person1":{"name":["Frida Larsson"],"age":["1"]}},
{"person2":{"name":["Abdi Sabrie"],"age":["2"]}},
{"person3":{"name":["Achraf Malak"],"age":["3"]}},
{"person4":{"name":["Adam Anclair"],"age":["1"]}}

]

I've placed those arrays in an array named

var peopleArray= { people: [ parsedData ] };

So far so good. Now what I want is being able to access certain persons attribute. Like names or age. How do I target those attributes? I've tried to print those attributes with no luck. I tried:

alert (peopleArray.people[0].person1.name);

Whiched returns:

Uncaught TypeError: Cannot read property 'name' of undefined

How can I access those attributes?

2012-04-05 18:30
by nalas
Looks like you have a typo 'namn' - PseudoNinja 2012-04-05 18:32
FYI, peopleArray is not an array, it's an object - bfavaretto 2012-04-05 18:36
the type was when I converted my variabel name to something more understandable. I've edited that out now.

bfvaretto: is that a big problem for me? How can I access names for peoples? Or if that's not possible: how can I make it an array instead of an object? Skip parseJSON - nalas 2012-04-05 22:10



3

Apart from the typo ("namn") the problem is you're putting an array inside an array:

var peopleArray = { people: [ parsedData ] };

Since parsedData is an array then what you end up with is a structure like this:

// peopleArray
{ people :  [ [  { "person0" : ... }, ...  ] ]  }
//  oops -----^

See the problem? Since parsedData is a already an array the correct code would be:

var peopleArray = { people: parsedData };
2012-04-05 18:39
by Jordan Running
I see. I've tried using your suggestion:

var peopleArray = { people: parsedData };

But it makes no differences - I'm still not able to access my names by using: peopleArray.people[0].person1.name

Is still undefine - nalas 2012-04-05 22:12

What's the value of peopleArray.people? What's the value of peopleArray.people[0]? What about peopleArray.people[0].person1 - Jordan Running 2012-04-06 15:39
peopleArray.people[0] gives me [object Object] - nalas 2012-04-11 11:10
What does the object look like? (Use console.log() with Firebug or Web Inspector, not alert(). - Jordan Running 2012-04-11 17:36
Thx, that advice was very good. I didn't know that you could log-out the objects. With that knowledge I would have been able to solve this issue as it was just a matter of using e.g ['name'] instead of [0 - nalas 2012-05-16 15:06
Ads