[json] How to display a JSON representation and not [Object Object] on the screen

I am making an AngularJS 2 application with the beta version. I want to show a JSON representation of an object in my page, but it shows [Object Object] and not {key1:value1 ....}

From the component I can use:

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

and then in the template:

{{example}}

but if I have an array of objects and would like to print a list of these objects, how I can do it?

Using:

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

results in something like:

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

and so on. Is there a way to display those as JSON?

This question is related to json angular

The answer is


We can use angular pipe json

{{ jsonObject | json }}

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

Dumping object content as JSON can be achieved without using ngFor. Example:

Object

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

Markup

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

Output (ran through a beautifier for better readability, otherwise it is output in a single row)

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

I have also discovered a JSON formatter and viewer that displays larger JSON data more readable (similar to JSONView Chrome extension): https://www.npmjs.com/package/ngx-json-viewer

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

if you have array of object and you would like to deserialize them in compoent

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

then in template

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

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

To loop through JSON Object : In Angluar's (6.0.0+), now they provide the pipe keyvalue :

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

DO READ ALSO

To just display JSON

{{ object | json }}

If you want to see what you you have inside an object in your web app, then use the json pipe in a component HTML template, for example:

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

Tested and valid using Angular 4.3.2.


There are 2 ways in which you can get the values:-

  1. Access the property of the object using dot notation (obj.property) .
  2. Access the property of the object by passing in key value for example obj["property"]

Updating others' answers with the new syntax:

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