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

Fla*_*ash 2 html javascript format json angular

我有一个字符串 json 对象,我试图在 html 中格式化和显示它。我曾尝试使用JSON.parse()andJSON.stringify()但 typeof 仍然显示为字符串,并且显示为直线而不是 format 。我也试过了<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, "   ")

}
Run Code Online (Sandbox Code Playgroud)

HTML代码:

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


<!-- <pre>{{formatJSON | json}}</pre> -->
Run Code Online (Sandbox Code Playgroud)

期望输出:

期望输出

nir*_*aft 7

尝试这个:

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


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

width:100px;
height: 150px;

}
Run Code Online (Sandbox Code Playgroud)
<textarea id="json-textArea"></textarea>
Run Code Online (Sandbox Code Playgroud)

检查此堆栈闪电战的角度版本:在 Angular 中,您只需要通过json管道运行您的 JSON 数据就可以了。