Angular 2 pipe that transforms JSON object to pretty-printed JSON
I would like to add an even simpler way to do this, using the built-in json
pipe:
<pre>{{data | json}}</pre>
This way, the formatting is preserved.
I would create a custom pipe for this:
@Pipe({ name: 'prettyprint'})export class PrettyPrintPipe implements PipeTransform { transform(val) { return JSON.stringify(val, null, 2) .replace(' ', ' ') .replace('\n', '<br/>'); }}
and use it this way:
@Component({ selector: 'my-app', template: ` <div [innerHTML]="obj | prettyprint"></div> `, pipes: [ PrettyPrintPipe ]})export class AppComponent { obj = { test: 'testttt', name: 'nameeee' }}
See this stackblitz: https://stackblitz.com/edit/angular-prettyprint
As this is the first result on google, let me add a quick sum up:
if you only need to print JSON without proper formatting, the build-in
json
pipe suggested by Shane Hsu works perfectly:<pre>{{data | json}}</pre>
however, if you want to have a different output, you will need to create your own pipe as Thierry Templier suggested:
ng g generate pipe prettyjson
- in prettyjson.pipe.ts:
import { Pipe, PipeTransform } from '@angular/core';@Pipe({ name: 'prettyjson'})export class PrettyjsonPipe implements PipeTransform { transform(value: any, ...args: any[]): any { return JSON.stringify(value, null, 2) .replace(/ /g, ' ') // note the usage of `/ /g` instead of `' '` in order to replace all occurences .replace(/\n/g, '<br/>'); // same here }}
- Finally, and because we return HTML content, the pipe must be used inside an
innerHTML
function:
<div [innerHTML]="data | prettyjson"></div>