AngularJS format JSON string output

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', [])
  .controller('Ctrl', ['$scope',
    function($scope) {

      $scope.data = {
        a: 1,
        b: 2,
        c: {
          d: "3"
        },
      };

    }
  ]);
<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="[email protected]" data-semver="1.2.15" src="//code.angularjs.org/1.2.15/angular.js"></script>
  </head>

  <body ng-controller="Ctrl">
    <pre>{{data | json}}</pre>
  </body>

</html>

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)


You can use an optional parameter of JSON.stringify()

JSON.stringify(value[, replacer [, space]])

Parameters

  • value The value to convert to a JSON string.
  • replacer If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string. A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
  • space Causes the resulting string to be pretty-printed.

For example:

JSON.stringify({a:1,b:2,c:{d:3, e:4}},null,"    ")

will give you following result:

"{
    "a": 1,
    "b": 2,
    "c": {
        "d": 3,
        "e": 4
    }
}"

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:

https://github.com/mohsen1/json-formatter/

enter image description here