Created
March 20, 2015 17:43
-
-
Save ssnau/eb60c9beb9888d248f99 to your computer and use it in GitHub Desktop.
a super simple JSON stringify
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
function repeat(_char, num) { | |
return (new Array(num + 1)).join(_char); | |
} | |
function stringify(object, blanks) { | |
blanks = blanks || 4; | |
var leading = repeat(' ', blanks); | |
switch (true) { | |
case Array.isArray(object): | |
return "[" + object.map(function(item) {return stringify(item, blanks + 4)}).join(', ') + "]"; | |
break; | |
case (typeof object == "object"): | |
return "{\n" + Object.keys(object).map(function(key) { | |
return leading + '"' + key + '": ' + stringify(object[key], blanks + 4); | |
}).join(',\n') + "\n" + repeat(' ', blanks - 4) + "}"; | |
break; | |
case (typeof object == 'string'): | |
return '"' + object + '"'; | |
default: | |
return object + ""; | |
} | |
} | |
console.log(stringify( | |
{ | |
name: 'jack', | |
age: 18, | |
profile: { | |
city: 'beijing', | |
phone_number: 18911456678, | |
person: ['mary', 'ford', 'peak', {hello: 'james'}] | |
} | |
} | |
)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment