Angular 2 prettify JSON pipe filter

2020-04-11 05:11发布

问题:

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 on my actual application. The image below is the printed JSON which is similar to what I have on plnkr.

Can anyone shed a light why this is happening?

Plnkr sample: https://plnkr.co/edit/ZqOXS30XPTu9ponWFdgZ?p=preview

Code pipe:

    @Pipe({
  name: 'prettyprint'
})
export class PrettyPrintPipe {
   transform(val) {
    if(typeof(val) == "undefined" || typeof(val) == null) return ''; //check value before process it.
    return JSON.stringify(val, null, 2)
      .replace(/ /g, ' ')
      .replace(/\\n/g, '<br>');
  }
}

JS Object, I need to JSON.stingify the two objects so I can concat or add the childObj inside the parent.

var parentJSONObj = JSON.stringify(object)
var childObj = JSON.stringify(object) // in a diferent schema 
this.output = parentJSONObj.replace(replaceObj, childObj) // and need to replace a property inside childObj

so this.output is the final JSON structure which I think is already a JSON string, adding the pipe filter gives adds slashes. When I try JSON.parse(this.output) it gives me an error of Unexpected token o in JSON at position 214

回答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})
export class JsonPipe implements PipeTransform {
  transform(value: any): string { return JSON.stringify(value, null, 2); }
}

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



回答2:

Change div tag to pre tag,

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

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



回答3:

This is a CSS solution:

code {
   white-space: pre; 
}

I created a working plunker:

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