samedi 9 mai 2015

how to get values from json with unknown ammount of given elements

Given this json as example:

{"offspring0":"John"},
{"offspring1":"Anna"},
{"offspring2":"Peter}

I can know how many offspring are there with:

offspringCount = (jsonString.match(/offspring/g) || []).length; //jsonString is the json above

This would return 3. Now, how can i get the value of all those offsprings? I have tried:

json = JSON.parse(jsonString);
alert(json[0].offspring[0]);

But this throws Uncaught TypeError: Cannot read property '0' of undefined because offspring is not an array.

I also tried:

alert(json[0]."offspring0");

But getting Uncaught SyntaxError: Unexpected string

My intention is to loop through all the offspring[number] and get the values, was expecting something like this:

for(x=0; x<offspringCount; x++){
    alert(json[0].offspring[x]);
}

Note i do not handle the making of the JSON, i only request it to a server.

Aucun commentaire:

Enregistrer un commentaire