Possible Duplicate:
Find length (size) of an array in jquery
I have a json object returned from a php file as follows:-
{"food":[
{
"name" :"Belgian Waffles",
"price" :"$5.95",
"description":"two of our famous Belgian Waffles with plenty of real maple syrup",
"calories" :"650"
},
{
"name" :"Strawberry Belgian Waffles",
"price" :"$7.95",
"description":"light Belgian waffles covered with strawberries and whipped cream",
"calories" :"900"
},
{
"name" :"Berry-Berry Belgian Waffles",
"price" :"$8.95",
"description":"light Belgian waffles covered with an assortment of fresh berries and whipped cream",
"calories" :"900"
}
]}
This is essentially returning three food elements from the object. How can I get a count of the total number of elements being returned if the json data is dynamic and not known using jquery?
Assuming you’ve parsed the JSON (or jQuery has done it for you, which it will if you use its Ajax functions) and you have the resulting object in a variable, just do this:
(Note: There’s no such thing as a JSON object: before you parse JSON it’s a string; after you parse it it’s an object.)
EDIT: In a comment you said you wouldn’t know that the property is called
food– if you do know that there will be exactly one property and that property will be an array you can do this:If you don’t know that there will be exactly one property then your requirement is too vague: if there might be multiple properties which one would you want to check the length of?