I'm having trouble outputting a valid JSON string from an object as input without using JSON.stringify().
Here is my current complete implementation -
var my_json_encode = function(input) {
if(typeof(input) === "string"){
return '"'+input+'"'
}
if(typeof(input) === "number"){
return `${input}`
}
if(Array.isArray(input)) {
const formatedArrayMembers = input.map(value => my_json_encode(value)).join(',');
return `[${formatedArrayMembers}]`;
}
*****Trouble is 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"}
I feel that I'm close but something is missing in my logic, I've started at this for to long and need some guidance.
If I can get my object encoder to work, I'm sure I can recursively use it to check more complicated inputs such as:
Expected Output-> [1,"a",{"key1":"value1","key2":null,"key3":[4,"b"],"key5":{"inner1":"innerval1","inner2":9}}]
Related question I asked for an array to JSON string was solved here
JSON.stringifyhandles quite a few edge cases not included here, things like rejecting circular data structures and not includingundefinedproperties, functions, or Symbols, plus additional features such as areplacerfunction, pretty-printing, convertingInfinityandNaNtonull, and calling objects'.toJSONmethods. A full replacement for all this is a non-trivial task.