views:

47

answers:

2

Hi all. I know how to generate JSON from an object using JSON.stringify, or in my case the handy jquery-json from google code (http://code.google.com/p/jquery-json/).

Now this works fine, but the output is hard to read for humans. Is there an easy way / function / 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.

Cheers all. Ben

p.s. I'd like to do this ideally without adding any huge libraries - e.g. not prototype or YUI or whatever.

A: 

edit - check here: http://www.matsblog.com/stories/2075888/


Original answer removed; didn't address question.

no
thanks for the reply. What do you count as a newer browser? I'm using chrome 5.0.375 and Safari 5 and they both output as a string without whitespace. I'm looking for a stringify that adds tabs and newlines to make the output easier to read.
Ben Clayton
Whoops, didn't read your question carefully. http://www.matsblog.com/stories/2075888/
no
+1  A: 

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:

http://stackoverflow.com/questions/2614862/json-beautifier

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.

CD Sanchez
Fab - thank you. That's exactly what I was looking for.
Ben Clayton