Prettifying JSON strings with JSON.stringify()

• Craig

Something that I’m sure you will all be aware of is that you can “pretty print” a JavaScript object with JSON.stringify.

So for example, System.log(object) will log a flat JSON string to the console by default.

standard

The other week, one of guys that I’m working with on my current engagement pointed me towards the space parameter of JSON.stringify().

Here is the syntax from MDN:

stringifysyntax

Making use of this parameter will allow you to insert white space into the output JSON string for readability purposes.. which is a massive help when it comes to debugging a large object or saving it to a file as a string.

The screenshot below uses the following line of code:

System.log(JSON.stringify(object, null, 2);

I’m passing null in place of the replacer parameter because I’m not going to be using it.

stringifyparam

I’m still not sure why I hadn’t looked for this functionality in JavaScript as I’ve always use the indent parameter of JSON.dumps when doing similar stuff in Python. At least I know now though ;-)