I am trying to learn recursion in Javascript, so I figured I\'d rewrite the native JSON.stringify
function using recursion as a challenge to myself. I almost got my
Fundamentally, you are stringifying by cutting off the first property, stringifying that and then recursing of the rest of the object. IMHO this is not the way to go, the only reason to recurse is when there is a nested object, otherwise you should just iterate through the properties. As you've done it, you've made it much more difficult to tell if you are at the beginning of the object and should return that missing {
with your string.
In semi-pseudo code (leaving you some work to do yourself), you want something like this:
var my_stringify = function(obj) {
// check first for null / undefined / etc and return
var myJSON = "{";
// iterate through all the properties of the object
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
// check to see if this property is a string, number, etc
if (//...) {
myJSON += // the JSON representation of this value using p and obj[p]
}
if (// test for nested object) {
myJSON += my_stringify(obj[p]); // this is recursion!
}
if (// test for arrays) {
// arrays also need special handling and note that they might
// include objects or other arrays - more chances for recursion!
}
// note: functions should be ignored, they aren't included in JSON
}
}
return myJSON + "}";
}