Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function to stringify JSON with whitespace?

I am aware of the fact that for JSON whitespace matters. But, just for debug output, I would like to print JSON objects formatted, thus with tabs and newlines.

Is there a function in JavaScript for formatted JSON stringification?

like image 450
danijar Avatar asked May 16 '13 15:05

danijar


1 Answers

The third argument of JSON.stringify controls spacing. So you can do this, for example :

var o = {
  a: {c:34}
};

console.log(JSON.stringify(o, null, '\t'));

This logs

{
    "a": {
        "c": 34
    }
} 

This parameter can accept different kind of values :

The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will indented by this string (or the first ten characters of it).

Using a tab character mimics standard pretty-print appearance:

like image 55
Denys Séguret Avatar answered Oct 17 '22 10:10

Denys Séguret