skip to Main Content

On the following, the key c has a stringified value:

let obj = {
   a: "apple",
   b: 2,
   c: '{"p":"11","q":"22","r":{"x":"aa","y":"bb"}}'
   d: "3"
}

I need to parse this object. I may have multiple keys with stringified object data and some plain strings.

I tried by doing JSON.parse(obj) but it’s giving an error. I also tried with JSON.parse(JSON.stringify(obj)) but it returns the same result as the intial obj.

Is there any possible way to solve this case?

3

Answers


  1. You can loop over each entry of the object and use JSON.parse on each string value.

    let obj = { a: 1, b: 2, c: '{"p":"11","q":"22","r":{"x":"aa","y":"bb"}}' }
    for (const [key, val] of Object.entries(obj))
      if (typeof val === 'string') obj[key] = JSON.parse(val);
    console.log(obj);
    Login or Signup to reply.
  2. You use JSON.parse to parse JSON.

    obj isn’t JSON. It’s a JavaScript object.

    obj.c is a string of JSON. You can parse that.

    const result = JSON.parse(obj.c);
    
    Login or Signup to reply.
  3. This will replace all property values that successfully parses as JSON with the resulting object. It uses an exception handler to catch the cases where the string is not valid JSON.

    let obj = {
       a: "apple",
       b: 2,
       c: '{"p":"11","q":"22","r":{"x":"aa","y":"bb"}}',
       d: "3"
    }
    
    for (let key in obj) {
      try {
        if (typeof obj[key] === 'string' && obj[key].startsWith('{')) {
          obj[key] = JSON.parse(obj[key]);
        }
      }
      catch (ignore) {}
    }
    
    console.log(obj)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search