将字符串格式化为JSON对象以HTML格式显示在带有/ [(ngModel)]的textarea中

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

我有一个字符串json对象,我试图格式化并在html中显示。我尝试过使用JSON.parse()JSON.stringify()但是typeof仍然显示为一个字符串,它以直线显示而不是格式化。我也尝试过<pre> {{formatJson | json}}</pre>但仍然没有成功。

formatJSON: string  = '{"a":1,"b":2,"c":{"d":3, "e":4}}'

ngOnInit() {
  var test = json.parse(this.formatJSON);
  console.log(typeof test); //string
  this.formatJSON = JSON.stringify(test, null, "   ")

}

HTML代码:

<div>
  <textarea [(ngModel)]="formatJSON" class="text-area" cols="200" rows="10">
       {{formatJSON}}
  </textarea>
</div>


<!-- <pre>{{formatJSON | json}}</pre> -->

期望的输出:

Desired Output

javascript html json angular format
3个回答
2
投票

试试这个:

var data = {"a":1,"b":2,"c":{"d":3,"e":4}}


document.getElementById("json-textArea").innerHTML = JSON.stringify(data, undefined, 2);
textarea { 

width:100px;
height: 150px;

}
<textarea id="json-textArea"></textarea>

检查这个stackblitz的angular version:在Angular中你只需要通过json管道运行你的JSON数据就可以了。


1
投票

请试试这个。像下面一样更新您的JSON字符串

formatJSON = {“a”:1,“b”:2,“c”:{“d”:3,“e”:4}}

您可以在html中的formatJSON上应用角度管道,如{{formatJSON | JSON}}


1
投票

我已将它应用于角度对话框材质中

在ts文件中

this.response=JSON.stringify(JSON.parse(item.response_body), null, 2);

在HTML中

<mat-dialog-content>
  <pre class="response-class"> {{data.response}}   </pre>
</mat-dialog-content>

在css

 ::ng-deep .response-class {
white-space: pre-wrap;

}

只有它是有效的json才能成功,你可以使用漂亮的json来检查它http://jsonprettyprint.com/

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