Created
January 20, 2011 03:03
-
-
Save rednaxelafx/787321 to your computer and use it in GitHub Desktop.
Pretty print JavaScript objects (does not conform to JSON, because we don't want escape sequences in string literals)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isPlainObject(o) { | |
return o && toString.call(o) === '[object Object]' && 'isPrototypeOf' in o; | |
} | |
function isArray(o) { | |
return toString.call(o) == '[object Array]'; | |
} | |
function objectToString(val) { | |
var INDENT = ' '; | |
var lines = []; | |
_objectToString(val, 0, lines); | |
return lines.join('<br />'); | |
function _makeIndent(nestDepth) { | |
var indent = ''; | |
for (var i = 0; i < nestDepth; i++) { | |
indent += INDENT; | |
} | |
return indent; | |
} | |
function _makeLine(val, nestDepth, propName) { | |
var indent = _makeIndent(nestDepth); | |
propName = propName && propName + ': ' || ''; | |
return indent + propName + val; | |
} | |
function _objectToString(val, nestDepth, lines, propName) { | |
var indent = _makeIndent(nestDepth); | |
if (isPlainObject(val)) { | |
lines.push(indent + '{'); | |
for (var prop in val) { | |
_objectToString(val[prop], nestDepth + 1, lines, prop); | |
} | |
lines.push(indent + '}'); | |
} else if (isArray(val)) { | |
lines.push(indent + '['); | |
for (var i = 0; i < val.length; i++) { | |
_objectToString(val[i], nestDepth + 1, lines); | |
} | |
lines.push(indent + ']'); | |
} else { | |
lines.push(_makeLine(val, nestDepth, propName)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment