Angular 2美化JSON管道过滤器 [英] Angular 2 prettify JSON pipe filter

查看:277
本文介绍了Angular 2美化JSON管道过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

奇怪,我正在尝试以漂亮的格式打印JSON,但是我的JSON始终以\返回并且没有被漂亮地打印.

Strange I'm trying to print my JSON in pretty formatted way however my JSON keeps returning with \ and not being printed pretty.

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

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示例: https://plnkr.co/edit/ZqOXS30XPTu9ponWFdgZ?p=preview

Plnkr sample: 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.

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

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

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具有用于格式化JSON数据的内置管道.只需将HTML模板更改为此:

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.

以下是JSON管道的完整来源:

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); }
}

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

这篇关于Angular 2美化JSON管道过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆