Reputation: 1263
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.
Upvotes: 0
Views: 2055
Reputation: 199
There are a couple of things needed to get to the correct solution.
First, you don't have a base case for your recursion, so at the base level of each recursive trace, nothing is returned (i.e., undefined is implicitly returned). So first you must add a base case where ints, strings, booleans, and other primitive types, are converted to strings.
Second, you must also check that obj !== null
before your recursive call, because typeof(null)
evaluates to "object", strangely enough.
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 && obj !== null && 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() + '}'
}
}
if (obj !== undefined) {return String(obj)}
};
Upvotes: 1