How to print json data.

I have a json output array like this

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

I want to skip it and print all the names using javascript. I want it to be possible.

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

But I can not find the length of the json object using javascript.

+6
json javascript
source share
2 answers

response.data is an array objects, so it has a length property that can be used to repeat its elements.

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

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

An object does not automatically have a length property, because it is not an array. To iterate over the properties of an object, do the following:

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

In some cases, you may need to iterate over the properties of an object, but not the properties of a prototype object. If you get unnecessary stuff with a regular loop ... use Object.prototype hasOwnProperty :

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

The thing is, if it is / really JSON data, at some point it should have been a string, since 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, you have to catch it before it gets to the point that it is taken apart, and just print it.

+2
source share

All Articles