Quick Tip – Pretty Print JSON in the Browser | Salesforce Developers Blog

Often, I find myself wrangling some RESTful API from JavaScript, and I need a way to see the content of some JSON object. The console.log() API works well, but it’s not universally supported and sample pages sometimes need to actually show JSON on the page. If I’m using alert() or setting the content of some element on the page, this sort of result is less than useful:

All of the data is there, but it’s tricky to visually parse the result – is longitude a property of position? No – it’s a property of coords, which itself is a property of position. If only there were a way to pretty print JSON without pulling in a bunch of library code… Hang on – recent [1] versions of JSON.stringify() can take additional arguments – ‘replacer’ and ‘space’. Replacer is described thus:

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.

while space ’causes the resulting string to be pretty-printed’.

So… just call JSON.stringify(obj, null, ‘ ‘) and your JSON will be pretty printed:

MUCH better! You can use the same trick to drop JSON into an element in the page – just use the <pre> tag so that the formatting is preserved:

[1] The three argument JSON.stringify() was introduced in ECMAScript 5 and is supported in Firefox 3.5.4+, IE 8.0+, Chrome 4.0+, Safari 4.0+ and Opera 10.5+. If you’re also targeting older browsers, then json2.js from https://github.com/douglascrockford/JSON-js provides excellent support.

Stay up to date with the latest news from the Salesforce Developers Blog