amenoire amenoire - 2 months ago 15
AngularJS Question

AngularJS format JSON string output

I have AngularJS application, which collects data from input, transforms model into string using

and lets a user edit this model in such way that input fields get updated if the
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:

enter image description here

And not like it looks now:

enter image description here

Any ideas how this can be acomplished? If you need some additional info - don't hesitate asking. Every answer is highly appreciated and answered immidiately.

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.


You can use an optional parameter of 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