简体   繁体   中英

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 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

在此输入图像描述

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

Change div tag to pre tag,

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

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

This is a CSS solution:

code {
   white-space: pre; 
}

I created a working plunker:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM