I'm trying to replicate JSON.stringify() using recursion. I'm a bit confused as to why I'm getting undefined in my returned JSON string. Here's what I've done so far:
var testobj = {num:123,str:"This is a string",bool:true,o:{x:1,y:2},iamnull:null}
var count = 0
var stringifyJSON = function(obj) {
// your code goes here
if(obj === undefined){
return console.log("obj was undefined");
}
count = count + 1
if(count > 20){ //I put this here mostly to stop infinite loops assuming this function wouldn't occur over 20 times.
return console.log("failed")
}
var endarray = [];
if(obj !== undefined && typeof(obj)==='object'){ //If the object isn't undefined and the object is an object...
for(var prop in obj){
console.log('"' + prop + '"');
endarray.push(stringifyJSON(prop) +'"' + ':' +'"'+ stringifyJSON(obj[prop])) //push the items into the array, using recursion.
}
if(typeof(obj) !== undefined){
return '{' + endarray.join() + '}'
}
}
};
//end result is "{undefined":"undefined,undefined":"undefined,undefined":"undefined,undefined":"{undefined":"undefined,undefined":"undefined},undefined":"{}}"
//JSON values cannot be a function, a date, or undefined
Could someone indicate where I'm going wrong? With recursion I'm having a problem identifying the source of the issue.
endarray. But you are resetting it to an empty array in each iteration of your recursion. You need to declareendarrayoutside the recursive function and build up your results until you complete.typeof(obj) !== undefinedThis will always betrue. Don't usetypeofto check forundefined. It's a shortsighted and unnecessary hack that only causes problems.stringifyJSONto accept two parameters, check ifendarrayis defined, if yes, push values to the array, else createendarray. Though, note, nativeJSON.stringify()implementation can accept more than only an object or array as parameter.typeof obj !== 'undefined'obj !== undefined && typeof(obj)==='object'. Iftypeof objis"object", then you already know it's notundefined. Maybe you were trying to avoidnullinstead.