Suppose I copy a string into a textarea for example:
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
So I JSON.parse(str)
parse the string in JSON format, but I would like to display the result in a textarea or something similar and formatted-
Also, if you modify something in there and it's wrong, that's an error. Something similar to this website: https://jsonformatter.org/
My handler:
$scope.toParseJson= function (str) {
$scope.jsonValue = str;
}
$scope.validateJson= function (str) {
$scope.errors= JSON.parse(str);
}
my html
<textarea ng-change="toParseJson(str)" ng-model="str"></textarea><br>
{{errors}}<br>
<textarea ng-change="validateJson(str)" ng-model="jsonValue "></textarea>
1- How do I get that in the second textarea it appears ordering with its tabulations and differentiating?
2- Is there another elegant way to display the errors?
Validate a JSON
The JSON.parse() method throws a SyntaxError if the syntax is invalid:
Print a formatted JSON
The JSON.stringify() method converts an object to JSON, and accepts a third parameter with the number of spaces to use for each tab. I printed the result in a container that respects whitespace (eg: a
<pre>
or a<textarea>
).