尝试编写一个 Angular 2 管道,该管道将采用 JSON 对象字符串并将其以漂亮的打印/格式返回以显示给用户。
例如,需要这样:
{ “id”:1, “号码”:“K3483483344”, “州”:“CA”, “活跃”:真实 }
并返回在 HTML 中显示时看起来像这样的内容:
所以在我看来我可以有这样的东西:
<td> {{ record.jsonData | prettyprint }} </td>
我想添加一种更简单的方法来执行此操作,使用内置的
json
管道:
<pre>{{data | json}}</pre>
这样,格式就被保留了。
我会为此创建一个自定义管道:
@Pipe({
name: 'prettyprint'
})
export class PrettyPrintPipe implements PipeTransform {
transform(val) {
return JSON.stringify(val, null, 2)
.replace(' ', ' ')
.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
我曾经需要这个场景,并且多次需要它。我看到这个问题在 2021 年仍然很流行。所以我创建了一篇详细的帖子,解释如何不仅美化它,还为其添加颜色,并构建了一个小工具来玩。
2021+解决方案: 我构建了自己的自定义版本的管道(受到这个answer的启发),它不仅可以美化,还可以像 vscode 一样向 JSON 添加颜色。我不使用内置 JSON 管道,因为它不能满足我的全部目的。
如果您愿意,您还可以自由添加数轴和填充。
示例输出如下
全局样式表应包含根据您的主题的颜色,例如
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, '&').replace(/</g, '<').replace(/>/g, '>');
/* 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>
希望这有帮助🙂。
json
管道可以完美工作:
<pre>{{data | json}}</pre>
ng generate pipe prettyjson
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, ' ') // note the usage of `/ /g` instead of `' '` in order to replace all occurences
.replace(/\n/g, '<br/>'); // same here
}
}
innerHTML
函数内部使用管道:
<div [innerHTML]="data | prettyjson"></div>
JSON.stringify(displayValue, null, 2)
并且它完成了工作。
”的掩盖?