Reputation: 188
I want to parse a JSON Object that contains some value as a json string, note that I don't know those fields previously, so I can't do something like
obj[key]=JSON.parse(obj[key])
. I am looking for an easy way to do that,
obj={
Name:"{\"FirstName\":\"Douglas\",\"LastName\":\"Crockford\"}"
}
And I want to get
{
Name:{
FirstName:"Douglas",
LastName:"Crockford"
}
}
Upvotes: 6
Views: 11252
Reputation:
We'll write a handy little utility which maps a function over object properties:
function mapObject(obj, fn) {
const result = {};
for (const prop in obj) result[prop] = fn(obj[prop], prop);
return result;
}
Now you can create an object with all the JSON values in the input parsed by just saying
mapObject(obj, JSON.parse)
If you want to guard against property values which are not valid JSON, then
function parseJSON(x) {
try { return JSON.parse(x); }
catch (e) { return x; }
}
and then
mapObject(obj, parseJSON)
Upvotes: 0
Reputation: 2550
If you want to get paradoxical about it, you can handle arbitrarily nested versions of this scenario using the "reviver parameter". Start by stringifying
your object!
function parseJSON(k,v) {
try { return JSON.parse(v, parseJSON); }
catch(e) { return v; }
}
JSON.parse(JSON.stringify(obj), parseJSON);
Is that nifty, or is it just me?
Upvotes: 1
Reputation: 781004
You can simply loop over all the keys:
obj={
Name: "{\"FisrtName\":\"Douglas\",\"LastName\":\"Crockford\"}",
Other: "This isn't JSON"
};
for (var key in obj) {
try {
obj[key] = JSON.parse(obj[key]);
} catch(err) {
// ignore error, just leave it alone
}
}
console.log(obj);
Upvotes: 0
Reputation: 62556
You can always try/pass on every key:
a = {
a: 1,
b: JSON.stringify({a: 1, b: 2}),
c: 'asdf'
}
console.log(a);
new_a = {}
Object.keys(a).map((key) => {
try {
new_a[key] = JSON.parse(a[key]);
} catch(err) {
new_a[key] = a[key];
}
})
console.log(new_a);
Upvotes: 0
Reputation: 6482
You could use Object.keys(obj)
to get the property names to allow you to use JSON.parse()
Upvotes: 0