Issue
I have a string json object that I am trying to format and display in the html. I have tried using JSON.parse()
and JSON.stringify()
but the typeof is still showing as a string and it is displaying in a straight line instead of formatting . I also tried <pre> {{formatJson | json}}</pre>
and still no success.
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 Code:
<div>
<textarea [(ngModel)]="formatJSON" class="text-area" cols="200" rows="10">
{{formatJSON}}
</textarea>
</div>
<!-- <pre>{{formatJSON | json}}</pre> -->
Desired Output:
Solution
Try this:
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>
check this stackblitz for the angular version: In Angular you just need to run your JSON data through json
pipe and you will be fine.
Answered By - nircraft
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.