角2-在用户界面中显示格式化的JSON字符串

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

在我的应用中,我有一个API调用,该API返回具有以下(简化)结构的JSON:

{
   "prop1": "foo",
   "prop2": "bar",
   "details": "{\"title\": \"Sample Konfabulator Widget\", \"name\": \"main_window\", \"width\": 500, \"height\": 500}"
}

details道具包含从数据库读取的大字符串化JSON。

现在,在用户界面中,我想显示details道具的经过修饰和格式化的版本,例如:

enter image description here

我尝试过:

<pre>{{ apiResponse.details }}</pre>

但是整个JSON显示在一行中。

我尝试过的代码是:https://stackblitz.com/edit/angular-pkfgvf?file=src%2Fapp%2Fapp.component.ts

谢谢!

angular angular2-template
3个回答
0
投票

您的details它不是json对象,这就是为什么不对其进行解析,您需要将其包装在JSON.parse()

details: JSON.parse("{\"title\": \"Sample Konfabulator Widget\", \"name\": \"main_window\", \"width\": 500, \"height\": 500}")

Updated Demo


0
投票

如果您不想直接在对象中使用JSON.parse(),则可以创建将字符串对象转换为json的管道。


0
投票

请尝试这样。

在打字稿方面

document.getElementById("json").textContent = JSON.stringify(
  data,
  undefined,
  2
);

确保您使用的是前置标签。

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