将 JSON 对象转换为漂亮打印的 JSON 的 Angular 2 管道

问题描述 投票:0回答:6

尝试编写一个 Angular 2 管道,该管道将采用 JSON 对象字符串并将其以漂亮的打印/格式返回以显示给用户。

例如,需要这样:

{ “id”:1, “号码”:“K3483483344”, “州”:“CA”, “活跃”:真实 }

并返回在 HTML 中显示时看起来像这样的内容:

所以在我看来我可以有这样的东西:

<td> {{ record.jsonData | prettyprint }} </td>
javascript json filter angular pipe
6个回答
475
投票

我想添加一种更简单的方法来执行此操作,使用内置的

json
管道:

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

这样,格式就被保留了。


32
投票

我会为此创建一个自定义管道:

@Pipe({
  name: 'prettyprint'
})
export class PrettyPrintPipe implements PipeTransform {
  transform(val) {
    return JSON.stringify(val, null, 2)
      .replace(' ', '&nbsp;')
      .replace('\n', '<br/>');
  }
}

并以这种方式使用它:

@Component({
  selector: 'my-app',
  template: `
    <div [innerHTML]="obj | prettyprint"></div>
  `,
  pipes: [ PrettyPrintPipe ]
})
export class AppComponent {
  obj = {
    test: 'testttt',
    name: 'nameeee'
  }
}

请参阅此 stackblitz:https://stackblitz.com/edit/angular-prettyprint


30
投票

我曾经需要这个场景,并且多次需要它。我看到这个问题在 2021 年仍然很流行。所以我创建了一篇详细的帖子,解释如何不仅美化它,还为其添加颜色,并构建了一个小工具来玩。

2021+解决方案: 我构建了自己的自定义版本的管道(受到这个answer的启发),它不仅可以美化,还可以像 vscode 一样向 JSON 添加颜色。我不使用内置 JSON 管道,因为它不能满足我的全部目的。

如果您愿意,您还可以自由添加数轴和填充。

示例输出如下

Demo

全局样式表应包含根据您的主题的颜色,例如

styles.scss


pre { font-weight: 400; .number-line { color: #adadaf; } .string { color: #95c602; } .number { color: #f2b619; } .boolean { color: #0097f1; } .null { color: #727990; } .key { color: #fff; } }
管道源代码

@Pipe({ name: 'prettyjson', pure:true }) export class PrettyJsonPipe implements PipeTransform { transform(value: any, args: any[]): any { try { /** * check and try to parse value if it's not an object * if it fails to parse which means it is an invalid JSON */ return this.applyColors( typeof value === 'object' ? value : JSON.parse(value), args[0], args[1] ); } catch (e) { return this.applyColors({ error: 'Invalid JSON' }, args[0], args[1]); } } applyColors(obj: any, showNumebrLine: boolean = false, padding: number = 4) { // line number start from 1 let line = 1; if (typeof obj != 'string') { obj = JSON.stringify(obj, undefined, 3); } /** * Converts special charaters like &, <, > to equivalent HTML code of it */ obj = obj.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); /* taken from https://stackoverflow.com/a/7220510 */ /** * wraps every datatype, key for e.g * numbers from json object to something like * <span class="number" > 234 </span> * this is why needed custom themeClass which we created in _global.css * @return final bunch of span tags after all conversion */ obj = obj.replace( /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, (match: any) => { // class to be applied inside pre tag let themeClass = 'number'; if (/^"/.test(match)) { if (/:$/.test(match)) { themeClass = 'key'; } else { themeClass = 'string'; } } else if (/true|false/.test(match)) { themeClass = 'boolean'; } else if (/null/.test(match)) { themeClass = 'null'; } return '<span class="' + themeClass + '">' + match + '</span>'; } ); /** * Regex for the start of the line, insert a number-line themeClass tag before each line */ return showNumebrLine ? obj.replace( /^/gm, () => `<span class="number-line pl-3 select-none" >${String(line++).padEnd(padding)}</span>` ) : obj; } }
现在像这样在 HTML 中传递这些参数。如果不通过,默认值 

showNumberline

 为 false,
padding
 为 4

<pre [innerHTML]="dummyJsonObject | prettyjson: [true, 3]"></pre>
希望这有帮助🙂。


12
投票
由于这是谷歌上的第一个结果,让我快速总结一下:

  • 如果您只需要打印 JSON 而没有正确的格式,Shane Hsu 建议的内置

    json

     管道可以完美工作:
    <pre>{{data | json}}</pre>
    
    

  • 但是,如果您想要不同的输出,则需要按照 Thierry Templier 的建议创建自己的管道:

  1. ng generate pipe prettyjson
    
    
  2. 在 Prettyjson.pipe.ts 中:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'prettyjson' }) export class PrettyjsonPipe implements PipeTransform { transform(value: any, ...args: any[]): any { return JSON.stringify(value, null, 2) .replace(/ /g, '&nbsp;') // note the usage of `/ /g` instead of `' '` in order to replace all occurences .replace(/\n/g, '<br/>'); // same here } }

    最后,因为我们返回 HTML 内容,所以必须在
  1. innerHTML
     函数内部使用管道:
<div [innerHTML]="data | prettyjson"></div>
    

5
投票
由于我的变量以两种方式与 ngModel 绑定,所以我无法在 html 上执行此操作。我在组件方面使用了

JSON.stringify(displayValue, null, 2)

 并且它完成了工作。 


0
投票
但是你如何摆脱“??

”的掩盖?

© www.soinside.com 2019 - 2024. All rights reserved.