How to print json data.
I have a json output array like this
{
"data": [
{
"name": "Ben Thorpe",
"id": "XXXXXXXXXXX"
},
{
"name": "Francis D开发者_开发百科avid",
"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.
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 + ', ';
}
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.
精彩评论