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
You can loop over each entry of the object and use
JSON.parse
on each string value.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.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.