Struggling to generate a correct JSON string from an object without relying on JSON.stringify().
Presenting my current implementation below -
var my_json_encode = function(input) {
if(typeof(input) === "string"){
return '"'+input+'"'
}
if(typeof(input) === "number"){
return `${input}`
}
if(Array.isArray(input)) {
const formattedArrayMembers = input.map(value => my_json_encode(value)).join(',');
return `[${formattedArrayMembers}]`;
}
*****Issue lies here*******
if(typeof(input) === "object" && !Array.isArray(input)) {
let temp = "";
for (let [key, value] of Object.entries(input)) {
let val = `${key} : ${value}`;
temp += my_json_encode(val)
}
return `{${temp}}`
}
}
Current input is -> {"key1":"val1","key2":"val2"}
Expected output is -> {"key1":"val1","key2":"val2"}
Current output using object type check in my_json_encode -> {"key1 : val1""key2 : val2"}
Feels like I'm close but there's a missing piece in my logic. Been staring at this for too long and could use some guidance.
If I can get the object encoder working, I believe I can recursively apply it to handle more complex inputs like:
Expected Output-> [1,"a",{"key1":"value1","key2":null,"key3":[4,"b"],"key5":{"inner1":"innerval1","inner2":9}}]
Had a similar question regarding converting an array to a JSON string answered here