如何在屏幕上显示JSON表示而不是[Object Object]

时间:2016-01-18 21:12:38

标签: json angular

我正在使用测试版制作AngularJS 2应用程序。我想在页面中显示对象的JSON表示,但它显示[Object Object]而不显示{key1:value1 ....}

从我可以使用的组件:

get example() {return JSON.stringify(this.myObject)};

然后在模板中:

{{example}}

但如果我有一个对象数组并想打印这些对象的列表,我该怎么做呢?

使用:

<ul>
   <li *ngFor="#obj of myArray">{{obj}}</li>
</ul>

导致类似:

- [Object Object]
- [Object Object]
- [Object Object]
- [Object Object]

等等。有没有办法将它们显示为JSON?

9 个答案:

答案 0 :(得分:146)

如果要查看Web应用程序中对象内部的内容,请在组件HTML模板中使用 json pipe ,例如:

<li *ngFor="let obj of myArray">{{obj | json}}</li>

使用Angular 4.3.2进行测试和有效。

答案 1 :(得分:44)

我们可以使用角管 json

{{ jsonObject | json }}

答案 2 :(得分:11)

要遍历JSON对象:在Angluar(6.0.0+)中,它们现在提供了管道keyvalue

<div *ngFor="let item of object| keyvalue">
  {{ item.key }} - {{ item.value }}
</div>

DO READ ALSO

仅显示JSON

{{ object | json }}

答案 3 :(得分:9)

可以在不使用ngFor的情况下将对象内容转储为JSON。例如:

<强>对象

export class SomeComponent implements OnInit {
    public theObject: any = {
        simpleProp: 1,
        complexProp: {
            InnerProp1: "test1",
            InnerProp2: "test2"
        },
        arrayProp: [1, 2, 3, 4]
    };

<强>标记

<div [innerHTML]="theObject | json"></div>

输出(通过美化器获得更好的可读性,否则输出为单行)

{
  "simpleProp": 1,
  "complexProp": {
    "InnerProp1": "test1",
    "InnerProp2": "test2"
  },
  "arrayProp": [
    1,
    2,
    3,
    4
  ]
}

我还发现了一个JSON格式化程序和查看器,它显示更大的JSON数据更具可读性(类似于JSONView Chrome扩展程序):https://www.npmjs.com/package/ngx-json-viewer

<ngx-json-viewer [json]="someObject" [expanded]="false"></ngx-json-viewer>

答案 4 :(得分:4)

您可以通过两种方式获取值: -

  1. 使用点表示法(obj.property)访问对象的属性。
  2. 通过传递键值来访问对象的属性,例如obj [&#34; property&#34;]

答案 5 :(得分:3)

<li *ngFor="let obj of myArray">{{obj | json}}</li>

答案 6 :(得分:2)

更新他人&#39;使用新语法的答案:

Country   Year    Orange  Apple Plump
US        2008    17      29     19
US        2009    11      12     16
US        2010    14      16     38
Spain     2008    11      NULL   33
Spain     2009    12      19     17
France    2008    17      19     21
France    2009    19      22     13
France    2010    12      11     15
Italy     2009    NULL    NULL   PRIVATE
Italy     2010    15      16     17
Italy     2011    42      NULL   PRIVATE

答案 7 :(得分:0)

如果您有对象数组,并且想在分量中反序列化它们

get example() { this.arrayOfObject.map(i => JSON.stringify (i) ) };

然后在模板中

<ul>
   <li *ngFor="obj of example">{{obj}}</li>
</ul>

答案 8 :(得分:0)

this.http.get<any>('http://192.168.1.15:4000/GetPriority')
  .subscribe(response => 
  {
  this.records=JSON.stringify(response) // impoprtant
  console.log("records"+this.records)
  });