Skip to content

Instantly share code, notes, and snippets.

@rebeccaryang
Created February 2, 2017 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rebeccaryang/f11b8dec16f541e14c6c97b34cb52383 to your computer and use it in GitHub Desktop.
Save rebeccaryang/f11b8dec16f541e14c6c97b34cb52383 to your computer and use it in GitHub Desktop.
// this is what you would do if you liked things to be easy:
// var stringifyJSON = JSON.stringify;
// but you don't so you're going to write it from scratch:
var stringifyJSON = function(obj) {
if(typeof(obj) === "number"){
return "" + obj + "";
} else if(obj === undefined){
return undefined;
} else if(obj === null){
return "null";
} else if(obj === true && typeof(obj) === "boolean"){
return "true";
} else if(obj === false && typeof(obj) === "boolean"){
return "false";
} else if(typeof(obj) === "string"){
return '"' + obj + '"';
} else if (typeof(obj) === "function"){
return obj;
} else if(Array.isArray(obj) && obj.length === 0){
return "[]";
} else if(Array.isArray(obj) && obj.length > 0){
var stringifyArr = ""
for(var i = 0; i < obj.length-1; i++){
stringifyArr += stringifyJSON(obj[i])+",";
}
stringifyArr += stringifyJSON(obj[obj.length-1]);
return "["+stringifyArr+"]";
} else {
var stringifyObj = "";
var objKeys = Object.keys(obj);
if (objKeys.length === 0){
return "{}";
} else {
for(var j = 0; j < objKeys.length-1; j++){
if (typeof(obj[objKeys[j]]) !== "function" && obj[objKeys[j]] !== undefined) {
stringifyObj += '"'+objKeys[j]+'":' + stringifyJSON(obj[objKeys[j]]) + ',';
}
}
if (typeof(obj[objKeys[objKeys.length-1]]) !== "function" && obj[objKeys[objKeys.length-1]] !== undefined) {
stringifyObj += '"'+objKeys[objKeys.length-1]+'":'+stringifyJSON(obj[objKeys[objKeys.length-1]]);
}
return "{"+stringifyObj+"}";
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment