Skip to content

Instantly share code, notes, and snippets.

@maolion
Last active August 9, 2016 03:11
Show Gist options
  • Save maolion/7255f710a0cccf55359d43ea35265384 to your computer and use it in GitHub Desktop.
Save maolion/7255f710a0cccf55359d43ea35265384 to your computer and use it in GitHub Desktop.
function stringify(obj, whitespace, isChild) {
if (!obj) {
return 'null';
}
var output = (obj instanceof Array ? '[' : '{') + '\n';
for (var i = 0, keyList = Object.keys(obj), l = keyList.length; i < l; i++ ) {
var key = keyList[i];
var prop = obj[key];
var stringifyValue = 'null';
if (prop != null) {
switch (typeof prop) {
case "boolean":
case "number":
stringifyValue = prop;
break;
case "string":
stringifyValue = '"'+ prop +'"';
break;
default:
if (prop instanceof RegExp ||
prop instanceof Number ||
prop instanceof Boolean
) {
stringifyValue = prop.toString();
} else if (prop instanceof String) {;
stringifyValue = '"' + prop.toString() + '"';
} else if (prop instanceof Function) {
stringifyValue = prop.toString().replace(/\r?\n/g, '\n' + whitespace);
} else {
stringifyValue = stringify(prop, whitespace + whitespace, true);
}
break;
}
}
output += whitespace + key + ' = ' + stringifyValue + ';\n';
}
output += (isChild ? whitespace.slice(0, whitespace.length / 2) : '') + (obj instanceof Array ? ']' : '}');
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment