494

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
np_6
5081 gold badge7 silver badges20 bronze badges
asked Apr 10, 2010 at 20:30
3
  • Why do you need to beautify it programmatically? Is it being displayed on a web page? Commented Apr 10, 2010 at 20:49
  • 3
    I'm rather amused to see so many "solutions" referenced in the answers, all solving a problem that is, per Andy E's answer, already catered for by the standard API. A lesson to us all: read the documentation of existing APIs before either seeking or implementing a solution to a requirement ;-) Commented Jul 10, 2011 at 1:30
  • If someone is looking for this stackoverflow.com/a/39183263/9295698 Commented May 21, 2024 at 23:39

1 Answer 1

995

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/ 

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.

answered Apr 10, 2010 at 20:33
Sign up to request clarification or add additional context in comments.

8 Comments

Awesome...thanks! (It might be worth adding that white-space:pre in the css is needed as well)
on html page, wrap your output in <pre></pre> tags
I use JSON.stringify and toastr to output for debugging. Live Example
Knew about null, 2, but didn't know that '\t' would work too. Fantastic!
I find jsonlint.com a little cumbersome. A MUCH quicker workflow is kadebom.com/jsonlint.html IMO
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.