I'm trying to write a function that takes some object, for example a number, a string, a list, or a map (of key-value pairs); and returns a valid JSON representation of that input as a string.
I have already set up other json encoders for simple numbers and string inputs:
Input => Output
a number with value 123 => 123 (string)
a string with value abc => "abc" (string)
But I'm having issues converting an array such as [1,"2",3]
Input => Output
1,2,three array => [1,2,"three"] (string)
Here is my current code:
var my_json_encode = function(input) {
if(typeof(input) === "string"){
return '"'+input+'"'
}
if(typeof(input) === "number"){
return `${input}`
}
//This is causing my issue
if(Array.isArray(input)) {
console.log(input)
}
I could simply add and return JSON.stringify(input) to change it but I don't want to use that. I know I can create some sort recursive solution as I have base cases set up for numbers and strings. I'm blocked on this and any help will be appreciated
Edit: So the solution as been provided below in the answers section! Thanks :)
'"'+input+'"'is not enough to produce valid JSON. Think what will happen ifinputcontains a"...