Skip to content Skip to sidebar Skip to footer

Angular 2 Prettify Json Pipe Filter

Strange I'm trying to print my JSON in pretty formatted way however my JSON keeps returning with \ and not being printed pretty. I have this solution which works on plnkr but not o

Solution 1:

Angular 2 has a built-in pipe for formatting JSON data. Just change your HTML template to this:

<pre>{{ x | json }}</pre>

Your custom pipe is simply replicating a native feature.

Below is the full source of the JSON pipe:

@Pipe({name: 'json', pure: false})
exportclassJsonPipeimplementsPipeTransform {
  transform(value: any): string { returnJSON.stringify(value, null, 2); }
}

See: https://github.com/angular/angular/blob/master/modules/@angular/common/src/pipes/json_pipe.ts

Solution 2:

Change div tag to pre tag,

<pre [innerHTML]="x | prettyprint"></pre>

DEMO : https://plnkr.co/edit/bpisrwlf2aFZFteapwY1?p=preview

Solution 3:

This is a CSS solution:

code {
   white-space: pre; 
}

I created a working plunker:

https://plnkr.co/edit/wULnv7b3tsKrML6hslWu?p=preview

Solution 4:

2021 update: I built my own custom version of pipe which not only prettifies but also add colors to json like vscode. Documented how to create that pipe here on the blog post

Source code of the pipe available on my Github repo

Sample output:

see output

You can try out this at

Run prettyjson ๐Ÿš€

Hope this helps๐Ÿ™‚

Post a Comment for "Angular 2 Prettify Json Pipe Filter"