views:

41

answers:

2

Hi,

I have a json output array like this

{
   "data": [
      {
         "name": "Ben Thorpe",
         "id": "XXXXXXXXXXX"
      },
      {
         "name": "Francis David",
         "id": "XXXXXXXXXXX"
      },
}

I want to loop through it and print out the all the names using javascript. I want to be able to do this.

for(i=0;i<length;i++){
      var result += response.data[i].name + ', ';
}

but i am unable to find the length of the json object using javascript.

I appreciate any help.

Thanks

+2  A: 

response.data is an array of objects, thus has a length property that you can use to iterate its elements.

var result;

for(var i=0;i<response.data.length;i++)
{
      result += response.data[i].name  + ', ';

}
Sky Sanders
A: 

If you just want to look at it for debugging purposes, do a console.log(myObject) or console.dir(myObject) and take a look at the firebug/chrome/safari console.

The object doesn't automatically have a length property because it's not an array. To iterate over properties of an object, do something like this:

for (var p in location) {
  console.log(p + " : " + location[p]);
}

In some cases you may want to iterate over properties of the object, but not properties of the object's prototype. If you're getting unwanted stuff with the regular for..in loop, use Object.prototype's hasOwnProperty:

for (var p in location) if (location.hasOwnProperty(p)) {
  console.log(p + " : " + location[p]);
}

The thing is, if this is/was really JSON data, it should have been a string at some point, as JSON is by definition a string representation of an object. So your question "How to print json data" almost reads like "How to print a string." If you want to print it out, you should be able to catch it before it gets to whatever parsed it into that object and just print it out.

no
Sorry, response.data is most certainly an array and thus has a length property. While your answer is accurate for a literal map or 'associative array' is is not relevant to this question.
Sky Sanders
Hmm, he is trying to iterate over an array isn't he? The missing closing bracket and outer object literal threw me off, I thought he was trying to iterate over an Object created from JSON.parse() or similar. Actually, for..in will work fine even if the object is an array... should work just as well as using '.length' as long as Array.prototype hasn't been messed with.
no
honest mistake. and sure, for-in can/may work, but i tend to favor code that just works. ;-)
Sky Sanders