0

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.

7
  • 1
    With recursion you are trying to accumulate a result of some sort. In this case endarray. But you are resetting it to an empty array in each iteration of your recursion. You need to declare endarray outside the recursive function and build up your results until you complete. Commented Mar 7, 2017 at 1:27
  • typeof(obj) !== undefined This will always be true. Don't use typeof to check for undefined. It's a shortsighted and unnecessary hack that only causes problems. Commented Mar 7, 2017 at 1:29
  • You can define stringifyJSON to accept two parameters, check if endarray is defined, if yes, push values to the array, else create endarray. Though, note, native JSON.stringify() implementation can accept more than only an object or array as parameter. Commented Mar 7, 2017 at 1:32
  • If you do use typeof it'll need to be compared to a string. Rewritten: typeof obj !== 'undefined' Commented Mar 7, 2017 at 1:33
  • Also, this is more verbose than needed: obj !== undefined && typeof(obj)==='object'. If typeof obj is "object", then you already know it's not undefined. Maybe you were trying to avoid null instead. Commented Mar 7, 2017 at 1:36

1 Answer 1

1

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)}


};
Sign up to request clarification or add additional context in comments.

3 Comments

This was so far the closest answer as it returns the testobj thrown in, but the quotes are just in the wrong places in the answer.
Glad to help. I did notice the quotation issue, but your original question asked about the undefineds, so that's what I focused on. Hopefully you're able to figure out the quotes yourself, but if not, feel free to write back for more help. :)
I wrote a jsfiddle trying the same thing and I think I got it right. jsfiddle.net/Vinilux/b7a4oy9w/59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.