1

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

1
  • 1
    Note that '"'+input+'"' is not enough to produce valid JSON. Think what will happen if input contains a "... Commented Apr 27, 2020 at 20:08

2 Answers 2

1

For arrays take a recursive approach with the items.

const
    json_encode = (input) => {
        if (typeof input === "string") return `"${input}"`;
        if (typeof input === "number") return `${input}`;
        if (Array.isArray(input)) return `[${input.map(json_encode)}]`;
    };

console.log(json_encode([1, 'foo', [2, 3]]));
console.log(JSON.parse(json_encode([1, 'foo', [2, 3]])));

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

2 Comments

you need a check for objects and exclude null in advance. if a value is undefined remove this value.
So i'm very close to the object and nested object implementation, I've added my code above below the edit. Let me know what I'm missing :)
1

You already have the function that converts scalar values to json values.

So, you can call this function for all array's member (e.g. using https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and then join it (https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/join) and add '[' and ']' to the resulting string

PS: this approach will work also in situations when you have an array of arrays

Example of the 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}]`;
   }
}

Comments

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.