Created
June 30, 2015 01:27
-
-
Save gartenfeld/f9a4f96ef5bb52425e6c to your computer and use it in GitHub Desktop.
Experiment with stringifyJSON.
This file contains hidden or 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 (obj===null) { | |
return 'null'; | |
} else if (typeof obj === 'number' || 'boolean') { | |
return obj.toString(); | |
} else if (typeof obj === 'string') { | |
return '"' + obj + '"'; | |
} else if (Array.isArray(obj)) { | |
var arrayString = "["; | |
for (var i=0; i<obj.length; i++) { | |
if (i) { | |
arrayString += "," | |
} | |
arrayString += stringifyJSON(obj[i]); | |
} | |
arrayString += "]"; | |
return arrayString; | |
} else if (obj.contructor === Object) { | |
var hashItems = []; | |
for (var key in obj) { | |
if (typeof obj[key] === 'function') { | |
return ""; | |
} | |
hashItems.push('"'+key+'":'+stringifyJSON(obj[key])); | |
} | |
return "{" + hashItems.join(',') + "}" | |
} else { | |
return ""; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment