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>
Solution 3:
This is a CSS solution:
code {
white-space: pre;
}
I created a working plunker:
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:
You can try out this at
Run prettyjson ๐
Hope this helps๐
Post a Comment for "Angular 2 Prettify Json Pipe Filter"