I'm programming in Rhino and I wasn't satisfied with any of the answers that were posted here. So I've written my own pretty printer:
function pp(object, depth, embedded) { typeof(depth) == "number" || (depth = 0) typeof(embedded) == "boolean" || (embedded = false) var newline = false var spacer = function(depth) { var spaces = ""; for (var i=0;i<depth;i++) { spaces += " "}; return spaces } var pretty = "" if ( typeof(object) == "undefined" ) { pretty += "undefined" } else if ( typeof(object) == "boolean" || typeof(object) == "number" ) { pretty += object.toString() } else if ( typeof(object) == "string" ) { pretty += "\"" + object + "\"" } else if ( object == null) { pretty += "null" } else if ( object instanceof(Array) ) { if ( object.length > 0 ) { if (embedded) { newline = true } var content = "" for each (var item in object) { content += pp(item, depth+1) + ",\n" + spacer(depth+1) } content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"") pretty += "[ " + content + "\n" + spacer(depth) + "]" } else { pretty += "[]" } } else if (typeof(object) == "object") { if ( Object.keys(object).length > 0 ){ if (embedded) { newline = true } var content = "" for (var key in object) { content += spacer(depth + 1) + key.toString() + ": " + pp(object[key], depth+2, true) + ",\n" } content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"") pretty += "{ " + content + "\n" + spacer(depth) + "}" } else { pretty += "{}"} } else { pretty += object.toString() } return ((newline ? "\n" + spacer(depth) : "") + pretty) }
The output looks like this:
js> pp({foo:"bar", baz: 1}) { foo: "bar", baz: 1 } js> var taco js> pp({foo:"bar", baz: [1,"taco",{"blarg": "moo", "mine": "craft"}, null, taco, {}], bleep: {a:null, b:taco, c: []}}) { foo: "bar", baz: [ 1, "taco", { blarg: "moo", mine: "craft" }, null, undefined, {} ], bleep: { a: null, b: undefined, c: [] } }
I've also posted it as a Gist here for whatever future changes may be required.