Created
August 8, 2014 17:46
-
-
Save ErBlack/05f9a9ece8312733282a to your computer and use it in GitHub Desktop.
Format prtint ob json
This file contains 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
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