Skip to content Skip to sidebar Skip to footer

Very Basic Json Question

I have this JSON data: var people = [ { name : 'John', age : 25 }, { name : 'Jane', age : 49 }, { name : 'Jim', age : 31 }, { name : 'Julie', age : 39 },

Solution 1:

Use a for loop: http://www.w3schools.com/js/js_loop_for.asp

for (var i = 0; i < people.length; i++)
{
     document.write(people[i].name + ' ' + people[i].age + '<br />'); 
}

or the each function in jQuery: http://api.jquery.com/jQuery.each/

$.each(people, function(i, o) {
   document.write(o.name + ' ' + o.age + '<br />'); 
});

Solution 2:

Not sure how you want to write it to the page, but here's a sample with document.write:

for (var i = 0, ilen = people.length; i < ilen; i++)
{
   document.write(people[i].name + ' ' + people[i].age + '<br/>');
}

I highly recommend getting the length in the first expression of for-loop, not the second. In this case, people.length is not too expensive. But if it is costly and you put it in the second expression like so for (var i = 0; i < people.length; i++), then it'll get evaluated in every loop and you wonder where your CPU cycles went. :)

Solution 3:

With jquery you can do

$.each(people, function(){
  alert(this.name + " " + this.age);
});

If you want to just append it to a div you can do

$.map(people, function(){
  returnthis.name + " " + this.age + "<br/>";
}).appendTo("#myDiv");

Solution 4:

Loop through them. These are Javascript object literals not JSON though, just FYI

for(var i = 0; i < people.length; i++) {
    alert(people[i].name + " " + people[i].age)
}

For example:

var variable = { 'key': 'value' };  // objectconsole.log(variable.key); // outputs: valuevar json = '{"key":"value"}'; // javascript string representing valid jsonconsole.log(json.key); // outputs: undefinedvar jObj = JSON.parse(json); // now a javascript object from the json stringconsole.log(jObj.key); // outputs: value    

So JSON only really exists in javascript as a representation.

Solution 5:

I'd use forEach:

people.forEach(function(person) {
    console.log(person.name, person.age)
});

Post a Comment for "Very Basic Json Question"