Angular 2美化JSON管道过滤器

nCo*_*ore 2 javascript angular

奇怪我正在尝试以相当格式化的方式打印我的JSON,但是我的JSON一直在返回\并且没有被打印得漂亮.

我有这个解决方案适用于plnkr但不适用于我的实际应用程序.下面的图片是打印的JSON,类似于我在plnkr上的内容.

任何人都可以解释为什么会这样吗?

Plnkr示例:https://plnkr.co/edit/ZqOXS30XPTu9ponWFdgZ p = preview

代码管道:

    @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>');
  }
}
Run Code Online (Sandbox Code Playgroud)

JS对象,我需要JSON.stingify两个对象,所以我可以concatchildObj在父对象内部添加.

在此输入图像描述

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
Run Code Online (Sandbox Code Playgroud)

this.output最后的JSON结构也是如此,我认为它已经是一个JSON字符串,添加管道过滤器会添加斜杠.当我尝试JSON.parse(this.output)它给我一个错误Unexpected token o in JSON at position 214

在此输入图像描述

Dan*_*son 7

Angular 2有一个用于格式化JSON数据的内置管道.只需将您的HTML模板更改为:

<pre>{{ x | json }}</pre>
Run Code Online (Sandbox Code Playgroud)

您的自定义管道只是复制本机功能.

以下是JSON管道的完整源代码:

@Pipe({name: 'json', pure: false})
export class JsonPipe implements PipeTransform {
  transform(value: any): string { return JSON.stringify(value, null, 2); }
}
Run Code Online (Sandbox Code Playgroud)

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