Skip to content

Instantly share code, notes, and snippets.

@ssnau
Created March 20, 2015 17:43
Show Gist options
  • Save ssnau/eb60c9beb9888d248f99 to your computer and use it in GitHub Desktop.
Save ssnau/eb60c9beb9888d248f99 to your computer and use it in GitHub Desktop.
a super simple JSON stringify
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