Created
February 2, 2017 23:09
-
-
Save rebeccaryang/f11b8dec16f541e14c6c97b34cb52383 to your computer and use it in GitHub Desktop.
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
// 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