How can I beautify JSON programmatically? [duplicate]
Asked Answered
N

1

480

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
Nephrectomy answered 10/4, 2010 at 20:30 Comment(2)
Why do you need to beautify it programmatically? Is it being displayed on a web page?Stephenson
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 ;-)Cortezcortical
R
969

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.

Rosaniline answered 10/4, 2010 at 20:33 Comment(8)
Awesome...thanks! (It might be worth adding that white-space:pre in the css is needed as well)Shadrach
on html page, wrap your output in <pre></pre> tagsBuchanan
I use JSON.stringify and toastr to output for debugging. Live ExampleWallis
Knew about null, 2, but didn't know that '\t' would work too. Fantastic!Moleskin
I find jsonlint.com a little cumbersome. A MUCH quicker workflow is kadebom.com/jsonlint.html IMOCircumscissile
@Circumscissile cumbersome? Literally copy, paste, click...Contempt
JSON.stringify does fairly horrible job on lists with lots of numbers, the npm package beautify-json (npm.io/package/beautify-json) does that better.Diatropism
question was about json string as an input NOT object, so proper would be ` JSON.stringify(JSON.parse(jsonString),null,2); `Savaii

© 2022 - 2024 — McMap. All rights reserved.