views:

1200

answers:

6
+3  Q: 

JSON Beautifier

Hi,

do you know any "JSON Beautifier"? Thanks!

From

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

To

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

Example

some_magic(jsonObj); // return beauty json file
+3  A: 

Well, if you paste the JSON into JSONlint you get formatted output.

Esko
He wants to be able to beautify the JSON from JavaScript, programmatically.
musicfreak
@musicfreak: He edited that in *after* I answered :)
Esko
A: 

jsonformat.com/

svinto
+1  A: 

Just paste it into: http://www.jsonlint.com/

Validation and beautification :)

If you just want beautification, this works on JSON as well as any javascript code: http://jsbeautifier.org/

Nick Craver
+1  A: 

jsbeautifier.org

Result:

{
    "name": "Steve",
    "surname": "Jobs",
    "company": "Apple"
}
Pekka
+5  A: 

Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time :-)

undeleted after your edit

If you want to do this programmatically, 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

This method is also included with json2.js. IE8/Chrome/Safari example at http://jsbin.com/asoya3/edit

Andy E
This is exactly what I was looking for! Thank you so much!
Randy Mayer
@Randy: np, I'm just glad I was able to change my answer from useless to useful ;-)
Andy E
Where's the rest of @Andy E? What happened?
Pekka
@Pekka: tragic accident ;-) In the name of science, my head was saved.
Andy E
@Andy Oh my! Glad to hear you're (somewhat) okay. You *could* start a support group with Welbog now :D http://meta.stackoverflow.com/questions/30419/welbogs-birthday-thread/30464#30464
Pekka
@Pekka: lol I just might ;-)
Andy E
A: 

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

Cheers!
Shonzilla

Shonzilla