Skip to content

Instantly share code, notes, and snippets.

@ErBlack
Created August 8, 2014 17:46
Show Gist options
  • Save ErBlack/05f9a9ece8312733282a to your computer and use it in GitHub Desktop.
Save ErBlack/05f9a9ece8312733282a to your computer and use it in GitHub Desktop.
Format prtint ob json
var format = function(value, indent) {
indent = indent || 1;
var tab = new Array(indent).join(' ');
switch (typeof value) {
case 'number':
case 'boolean':
return value;
break;
case 'string':
return '"' + value + '"';
break;
case 'object':
if (Array.isArray(value)) {
return value.reduce(function(result, item, index) {
result += format(item, indent + 1);
if (index < value.length - 1) {
result += ', ';
}
return result;
}, '[') + ']';
}
return Object.keys(value).reduce(function(result, name, index, array) {
result += ' ' + tab + name + ': ' + format(value[name], indent + 1);
if (index < array.length - 1) {
result += ',';
}
return result + '\n';
}, '{\n') + tab + '}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment