奇怪的是,我正在尝试以格式良好的方式打印我的 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
原文由 nCore 发布,翻译遵循 CC BY-SA 4.0 许可协议
Angular 2 有一个用于格式化 JSON 数据的内置管道。只需将您的 HTML 模板更改为:
您的自定义管道只是复制本机功能。
以下是 JSON 管道的完整源代码:
请参阅: https ://github.com/angular/angular/blob/master/modules/@angular/common/src/pipes/json_pipe.ts