How can I beautify JSON programmatically?

JavascriptJsonCode FormattingPretty Print

Javascript Problem Overview


Do you know of any "JSON Beautifier" for JavaScript?

From

{"name":"Steve","surname":"Jobs","company":"Apple"}

To

{
  "name" : "Steve",
  "surname" : "Jobs",
  "company" : "Apple"
}

Example

some_magic(jsonObj); // return beautified JSON

Javascript Solutions


Solution 1 - Javascript

Programmatic formatting solution:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level

Demo: http://jsfiddle.net/AndyE/HZPVL/">http://jsfiddle.net/AndyE/HZPVL/</a></pre>
This method is also included with json2.js, for supporting older browsers.

Manual formatting solution

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRandy MayerView Question on Stackoverflow
Solution 1 - JavascriptAndy EView Answer on Stackoverflow