For an assignment, I'm trying to implement the JSON.stringify functionality recursively.
However, my current approach - which attempts to directly return a string concatenating the object's key/value pairs - doesn't work because the parenthesis and commas are misplaced. Ideally, I would be able to recursively construct an array and then join the elements with commas, but am unsure how to do this. Any suggestions or alternative approaches?
Thank you!
var stringifyJSON = function(obj) {
if (typeof(obj) == "object") {
var newValue;
var objKeys = Object.keys(obj);
if (Object.keys(obj).length === 0) {
return "";
}
else if (Object.keys(obj).length !== 0) {
var key = (typeof(objKeys[0]) == "string") ? '"' + objKeys[0] + '"' : objKeys[0];
var value = (typeof(obj[objKeys[0]]) == "string") ? '"' + obj[objKeys[0]] + '"' : obj[objKeys[0]];
newValue = key + ":" + value;
delete obj[objKeys[0]];
}
return "{" + newValue + "," + stringifyJSON(obj) + "}";
}
};