Trying to write an Angular 2 pipe that will take a JSON object string and return it pretty-printed/formatted to display to the user.
For example, it would take this:
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
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
}
}
innerHTML
function:<div [innerHTML]="data | prettyjson"></div>
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
since my variable is two way binded with ngModel, I could not do it on html. I used on component side JSON.stringify(displayValue, null, 2)
and it did the job.
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.