I have an AngularJS application, which collects data from input, transforms a model into a string using JSON.stringify()
and lets a user edit this model in such a way that input fields get updated if the <textarea>
element is updated and vice versa. Some kind of two-way binding :)
The problem is that the String itself looks ugly and I would like to format it so it looks like this:
And not like it looks now:
Any ideas how this can be accomplished? If you need some additional info - don't hesitate asking. Every answer is highly appreciated and answered immediately.
Thank you.
P.S. I guess this should be some kind of directive or a custom filter. Data itself SHOULD NOT be changed, only the output.
This question is related to
javascript
json
string
angularjs
formatting
If you are looking to render JSON as HTML and it can be collapsed/opened, you can use this directive that I just made to render it nicely:
Angular has a built-in filter
for showing JSON
<pre>{{data | json}}</pre>
Note the use of the pre
-tag to conserve whitespace and linebreaks
Demo:
angular.module('app', [])_x000D_
.controller('Ctrl', ['$scope',_x000D_
function($scope) {_x000D_
_x000D_
$scope.data = {_x000D_
a: 1,_x000D_
b: 2,_x000D_
c: {_x000D_
d: "3"_x000D_
},_x000D_
};_x000D_
_x000D_
}_x000D_
]);
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="app">_x000D_
_x000D_
<head>_x000D_
<script data-require="[email protected]" data-semver="1.2.15" src="//code.angularjs.org/1.2.15/angular.js"></script>_x000D_
</head>_x000D_
_x000D_
<body ng-controller="Ctrl">_x000D_
<pre>{{data | json}}</pre>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
There's also an angular.toJson
method, but I haven't played around with that (Docs)
In addition to the angular json
filter already mentioned, there is also the angular toJson()
function.
angular.toJson(obj, pretty);
The second param of this function lets you switch on pretty printing and set the number of spaces to use.
If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.
(default: 2)
I guess you want to use to edit the json text. Then you can use ivarni's way:
{{data | json}}and add an adition attribute to make
editable
<pre contenteditable="true">{{data | json}}</pre>
Hope this can help you.
If you want to format the JSON and also do some syntax highlighting, you can use the ng-prettyjson
directive. See the npm package.
Here is how to use it: <pre pretty-json="jsonObject"></pre>
Source: Stackoverflow.com