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