JavaScript: How can I generate formatted easy-to-read JSON straight from an object? [duplicate]
Asked Answered
S

1

567

Possible Duplicate:
How can I beautify JSON programmatically?

I know how to generate JSON from an object using JSON.stringify, or in my case the handy jQuery JSON from Google Code.

Now this works fine, but the output is hard to read for humans. Is there an easy way, function, or whatever to output a neatly formatted JSON file?

This is what I mean:

JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}});

gives...

"{"a":1,"b":2,"c":{"d":1,"e":[1,2]}}"

I'd like something like this instead:

{
 "a":1,
 "b":2,
 "c":{
    "d":1,
    "e":[1,2]
 }
}

E.g., with newlines and tabs added. It's much easier to read for larger documents.

I'd like to do this ideally without adding any huge libraries, for example, not Prototype, YUI, or whatever.

Synergy answered 18/8, 2010 at 18:43 Comment(3)
Maybe this will help: jsoneditoronline.orgSaxhorn
Now you know why many prefer XML instead of JSON. Its much more readable.Duomo
@HermanVanDerBlom, a one-line XML would not be human readble either.Cornwallis
P
1237

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

It should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

Polynesian answered 18/8, 2010 at 19:11 Comment(4)
Isn't this answer a bit inaccurate given the OP wrote his beautified version with the "e":[1,2] all on one line? Is it possible to mix indented & non-indented JSON with stringify?Signorelli
Just remember to put it inside something like <pre> to get new lines.Hawkie
github.com/Phrogz/NeatJSON and npm.io/package/json-beautify privide some more control & options for programmatic stringification of JSON.Valero
You can use white-space: pre instead of a <pre>, if you prefer.Kinematics

© 2022 - 2024 — McMap. All rights reserved.