let obj = { a: 1, b: 2, c: '{"p":"11","q":"22","r":{"x":"aa","y":"bb"}}' }
Here one of the key (c) has stringified value.
I need to parse this object. Here we may have multiple keys with stringified data.
I tried by doing JSON.parse(obj) but it's giving error.
And also tried as JSON.parse(JSON.stringify(obj)) it's giving same result as obj initially.
Is there any possible way to solve this case ?
CodePudding user response:
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);
CodePudding user response:
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);