'Formatting a string to JSON Object to disply in HTML In a textarea w/ [(ngModel)]
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 1:[1]
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.
Solution 2:[2]
Please try this. Update your JSON string like below
formatJSON = {
"a": 1,
"b": 2,
"c": {
"d": 3,
"e": 4
}
}
You can apply angular pipe on formatJSON in your html like this {{formatJSON | json}}.
Solution 3:[3]
I have applied it in angular Dialog material like this
in ts file
this.response=JSON.stringify(JSON.parse(item.response_body), null, 2);
in html
<mat-dialog-content>
<pre class="response-class"> {{data.response}} </pre>
</mat-dialog-content>
in css
::ng-deep .response-class {
white-space: pre-wrap;
}
It will work fine if it's a valid json, you can use pretty json to check from it http://jsonprettyprint.com/
Solution 4:[4]
This is an easy way to show json, with the json pipe behaves the same as doing JSON.stringify(yourData) in your code
<pre>{{ yourData | json }}</pre>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Matt Cremeens |
| Solution 3 | nircraft |
| Solution 4 |

