0

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 ?

2
  • 1
    It seems like json is already a string so stringifying it isn't going to work properly. Try JSON.stringify(JSON.parse($scope.json), null, "\t") Commented Apr 9, 2015 at 20:06
  • @Explosion Pills you are right. Commented Apr 9, 2015 at 20:38

3 Answers 3

4

There 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

Sign up to request clarification or add additional context in comments.

4 Comments

it is working. but if you will take json from input in that case it will not work.
Can you clarify? You are entering in JSON in an input field you made and it's not formatting correctly?
Yeah, I see that. Are you trying to make a tool that creates JSON from user input? So, you would need to do some more stuff to make that work, you could have them enter an object name then save it to an array then that is what you print out, not the direct user input since that is messy. Does that make sense?
yes, you are right. but we can do it using this code: JSON.stringify(JSON.parse($scope.json), null, "\t")
2

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.com/nakazuhaqa/1/edit?html,js,output

Comments

1

Angular provides a helper for this:

angular.toJson(json, true);

https://docs.angularjs.org/api/ng/function/angular.toJson

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.