Trying to write an Angular 2 pipe that will take a JSON object string and return it pretty-printed/formatted to display to the user.
尝试编写一个角2管道,该管道将接收JSON对象字符串并将其漂亮地打印/格式化并显示给用户。
For example, it would take this:
例如,它会这样:
{ "id": 1, "number": "K3483483344", "state": "CA", "active": true }
{ " id ":1,“数量”:“K3483483344”,“状态”:“CA”、“活跃”:真正的}
And return something that looks like this when displayed in HTML:
返回HTML中显示的如下内容:
So in my view I could have something like:
所以在我看来
<td> {{ record.jsonData | prettyprint }} </td>
2 个解决方案
#1
136
I would like to add an even simpler way to do this, using the built-in json
pipe:
我想添加一个更简单的方法,使用内置的json管道:
<pre>{{data | json}}</pre>
This way, the formatting is preserved.
这样,格式就被保留了。
#2
6
I would create a custom pipe for this:
我将为此创建一个自定义管道:
@Pipe({
name: 'prettyprint'
})
export class PrettyPrintPipe implements PipeTransform {
transform(val) {
return JSON.stringify(val, null, 2)
.replace(' ', ' ')
.replace('\n', '<br/>');
}
}
and use it this way:
用这种方式:
@Component({
selector: 'my-app',
template: `
<div [innerHTML]="obj | prettyprint"></div>
`,
pipes: [ PrettyPrintPipe ]
})
export class AppComponent {
obj = {
test: 'testttt',
name: 'nameeee'
}
}
See this plunkr: https://plnkr.co/edit/WbywRZTrpBoX3UsROYuS?p=preview.
看到这个plunkr:https://plnkr.co/edit/WbywRZTrpBoX3UsROYuS?p=preview。
#1
136
I would like to add an even simpler way to do this, using the built-in json
pipe:
我想添加一个更简单的方法,使用内置的json管道:
<pre>{{data | json}}</pre>
This way, the formatting is preserved.
这样,格式就被保留了。
#2
6
I would create a custom pipe for this:
我将为此创建一个自定义管道:
@Pipe({
name: 'prettyprint'
})
export class PrettyPrintPipe implements PipeTransform {
transform(val) {
return JSON.stringify(val, null, 2)
.replace(' ', ' ')
.replace('\n', '<br/>');
}
}
and use it this way:
用这种方式:
@Component({
selector: 'my-app',
template: `
<div [innerHTML]="obj | prettyprint"></div>
`,
pipes: [ PrettyPrintPipe ]
})
export class AppComponent {
obj = {
test: 'testttt',
name: 'nameeee'
}
}
See this plunkr: https://plnkr.co/edit/WbywRZTrpBoX3UsROYuS?p=preview.
看到这个plunkr:https://plnkr.co/edit/WbywRZTrpBoX3UsROYuS?p=preview。