繁体   English   中英

Angular 2美化JSON管道过滤器

[英]Angular 2 prettify JSON pipe filter

奇怪我正在尝试以相当格式化的方式打印我的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>');
  }
}

JS对象,我需要JSON.stingify这两个对象,这样我就可以在父对象中concat或添加childObj

在此输入图像描述

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

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

在此输入图像描述

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

<pre>{{ x | json }}</pre>

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

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

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

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

div标签更改为pre标签,

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

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

这是一个CSS解决方案:

code {
   white-space: pre; 
}

我创建了一个工作的plunker:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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