Lipee
Lipee

Reputation: 260

Printing Information from JSON string

I have the following JSON string:

var txt= 
{
    "people": 
    [{
        "person": 
        {
            "firstname":"Jane",
            "lastname":"Doe"
        }
    },
     {
         "person":
         {
             "firstname":"John",
             "lastname":"Smith"
         }
     }
    ]
};

I want the program to alert that there are two people in the list, but when I do my count function, it only says 1 (gets to 'people' then doesn't go deeper into the list).

Here is the fiddle: http://jsfiddle.net/LipeeVora/rsBYb/3/

Upvotes: 1

Views: 80

Answers (4)

Alex
Alex

Reputation: 39

This should work:

txt.people.length 

You might have to do a JSON.parse depending on where you're pulling your JSON string from (if you're doing anything with it outside of the fiddle)

Upvotes: 1

user428517
user428517

Reputation: 4193

You don't need a to write a counting loop. txt.people.length will give you the count, as txt.people is an array object.

See my revised fiddle for an example: http://jsfiddle.net/rsBYb/5/


Your loop was counting the elements in txt - of which there is only one (the people array). It would work fine if you instead use txt.people in the loop. You really want to count the elements in txt.people, not txt.

Example of this: http://jsfiddle.net/rsBYb/8/

Upvotes: 3

Boris Chlopkov
Boris Chlopkov

Reputation: 76

It is because you count people and not persons. Change your loop to this:

for ( property in txt.person )
{
    count++;
}
alert("count = " + count);

Upvotes: 1

john Smith
john Smith

Reputation: 17906

txt.people.length 

will give you the correct answer

http://jsfiddle.net/rsBYb/6/

Upvotes: 1

Related Questions