467

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
  • 514
  • 1
  • 6
  • 19
Randy Mayer
  • 8,455
  • 8
  • 25
  • 11
  • Why do you need to beautify it programmatically? Is it being displayed on a web page? – SeanJA Apr 10 '10 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 ;-) – NickFitz Jul 10 '11 at 01:30

1 Answers1

946

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.

Community
  • 1
  • 1
Andy E
  • 338,112
  • 86
  • 474
  • 445