JSON - better readable output
This is a modified version of JSON in JavaScript which adds an option to pretty print the JSON output.
Download: JSON-js-prettyPrint (js, 5 KB)
on the client side it doesn't seem to make sense to pretty print the JSON output, because in most cases you will send it back to a server. but we use the script on the server side (using Helma/Rhino) so it makes perfectly sense for us.
Download: JSON-js-prettyPrint (js, 5 KB)
object.toJSONString(prettyPrint)
array.toJSONString(prettyPrint)
prettyPrint ... if set to true the resulting string will be formated
with tabs and returns to be more human readable.
Here is an example data object:
var data = {
"eins" : "Eins",
"int" : 2,
"number" : 2.234,
"obj" : {
"a" : "A", b:"B", c:"C"
},
"array" : ["eins","zwei","drei",{"vier":4,"null":null,"undefined":undefined},{"vier":4,"null":null,"undefined":undefined},"zwei","drei",{"vier":4,"null":null,"undefined":undefined}],
isBoolean : true
};
data.toJSONString() will ouput:
{"array":["eins","zwei","drei",{"vier":4,"null":null},{"vier":4,"null":null},"zwei","drei",{"vier":4,"null":null}],"eins":"Eins","obj":{"a":"A","b":"B","c":"C"},"number":2.234,"isBoolean":true,"int":2}
data.toJSONString(true) will ouput:
{
"array" : [
"eins",
"zwei",
"drei",
{
"vier" : 4,
"null" : null
},
{
"vier" : 4,
"null" : null
},
"zwei",
"drei",
{
"vier" : 4,
"null" : null
}
],
"eins" : "Eins",
"obj" : {
"a" : "A",
"b" : "B",
"c" : "C"
},
"number" : 2.234,
"isBoolean" : true,
"int" : 2
}
why i did it?on the client side it doesn't seem to make sense to pretty print the JSON output, because in most cases you will send it back to a server. but we use the script on the server side (using Helma/Rhino) so it makes perfectly sense for us.
matthias - 27. May, 11:03
1 comment - add comment - 0 trackbacks
Reid Kleckner (anonymous) - 4. Aug, 19:49
Typo?
Did you mean "INDENT" when you wrote "INTEND" in the source? Also, it's dangerous to modify the base Object.prototype because it makes for ... in loops behave badly. I'm going to mix your modifications in with a version of JSON that doesn't modify Object.prototype and I'll post the source on my blog. Awesome work!









Trackback URL:
http://www.matsblog.com/stories/2075888/modTrackback