I know how to beautify JSON programmatically using javascript. this way we can achieve:
var obj = {"hello":"world", "Test":["hello"]}
document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(JSON.stringify(obj, null, 4)));
But i tried to do it in angular js. but i am unable to achieve this. This is my step :
<div class="btn btn-primary" ng-click="test()">Press</div>
<textarea json-formatter rows="20" cols="140" ng-model="json">
</textarea>
$scope.test=function(){
var json=JSON.stringify($scope.json, null, "\t");
/*here if $scope.json is {"hello":"world", "Test":["hello"]}
then json return "{\"hello\":\"world\", \"Test\":[\"hello\"]}" */
}
here if $scope.json
is {"hello":"world", "Test":["hello"]}
then json
return "{\"hello\":\"world\", \"Test\":[\"hello\"]}"
.after that, i don't now how to display beautify json to same text area. How to resolve this problem. Is there any other approach then please suggest me ?
I know how to beautify JSON programmatically using javascript. this way we can achieve:
var obj = {"hello":"world", "Test":["hello"]}
document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(JSON.stringify(obj, null, 4)));
But i tried to do it in angular js. but i am unable to achieve this. This is my step :
<div class="btn btn-primary" ng-click="test()">Press</div>
<textarea json-formatter rows="20" cols="140" ng-model="json">
</textarea>
$scope.test=function(){
var json=JSON.stringify($scope.json, null, "\t");
/*here if $scope.json is {"hello":"world", "Test":["hello"]}
then json return "{\"hello\":\"world\", \"Test\":[\"hello\"]}" */
}
here if $scope.json
is {"hello":"world", "Test":["hello"]}
then json
return "{\"hello\":\"world\", \"Test\":[\"hello\"]}"
.after that, i don't now how to display beautify json to same text area. How to resolve this problem. Is there any other approach then please suggest me ?
-
1
It seems like
json
is already a string so stringifying it isn't going to work properly. TryJSON.stringify(JSON.parse($scope.json), null, "\t")
– Explosion Pills Commented Apr 9, 2015 at 20:06 - @Explosion Pills you are right. – Mukund Kumar Commented Apr 9, 2015 at 20:38
3 Answers
Reset to default 4There is a built in feature for filtering json {{Object | json }}
You can use the built in filter for your code
{{dataObject | json}}
Will beautify your json, give it a try.
Here is a working example:
http://plnkr.co/edit/DM1TbN3eXGngJaFgi6n6?p=preview
You can use Angular's built in json
filter to pretty print an object.
In your view you can use the filter as follows:
{{yourData | json}}
The indentation can be customised by passing a second numerical value into the filter:
{{yourData | json:4}}
A working example of this code can be found here: http://jsbin./nakazuhaqa/1/edit?html,js,output
Angular provides a helper for this:
angular.toJson(json, true);
https://docs.angularjs/api/ng/function/angular.toJson