display formatted json in the page

To Display formatted json we need to use
<pre> tag and stringify the js object.

Use JSON.Stringify

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


  • 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

Use angularjs built-in filter

If you are using angularjs, you can leverage the build in ‘| json’ filter.

<pre>{{data | json}}</pre>

Note the use of the pre-tag to conserve whitespace and linebreaks

Demo: http://plnkr.co/edit/lwqajlWvJGTaH0HTfnJd?p=preview

There’s also an angular.toJson method, but I haven’t played around with that (Docs)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s