Javascript 如何打印json数据。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3326820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:10:06  来源:igfitidea点击:

How to print json data.

javascriptjson

提问by Nick

I have a json output array like this

我有一个像这样的 json 输出数组

{
   "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.

我想遍历它并使用javascript打印出所有名称。我希望能够做到这一点。

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.

但是我无法使用 javascript 找到 json 对象的长度。

采纳答案by Sky Sanders

response.datais an arrayof objects, thus has a lengthproperty that you can use to iterate its elements.

response.data是一个arrayof 对象,因此具有一个length可用于迭代其元素的属性。

var result;

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

}

回答by Dagg Nabbit

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.

如果您只是为了调试目的而查看它,请执行console.log(myObject)console.dir(myObject)查看 firebug/chrome/safari 控制台。

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

该对象不会自动具有length属性,因为它不是数组。要迭代对象的属性,请执行以下操作:

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..in 循环获得不需要的东西,请使用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.

问题是,如果这真的是/曾经是 JSON 数据,那么它在某个时候应该是一个字符串,因为 JSON 根据定义是对象的字符串表示。所以你的问题“如何打印 json 数据”几乎读起来像“如何打印字符串”。如果你想把它打印出来,你应该能够在它到达任何将它解析成那个对象之前捕获它,然后将它打印出来。