Reputation: 25996
I would like to add a set of escaped quote around all first level keys in a JSON object.
const j = '{"a": "b", "c": "d"}';
let obj = JSON.parse(j);
Object.keys(obj).forEach(k => {
k = `\"${k}\"`;
});
console.log(JSON.stringify(obj, null, 2));
which of course gives
{
"a": "b",
"c": "d"
}
as I need to do the substitution in the actual object.
But how can I update the keys in place?
Upvotes: 1
Views: 261
Reputation: 2000
This should work. Just define a new key and give it the same value as the old key, then delete the old key.
const j = '{"a": "b", "c": "d"}';
let obj = JSON.parse(j);
Object.keys(obj).forEach(k => {
obj[`\"${k}\"`] = obj[k];
delete obj[k];
});
console.log(JSON.stringify(obj, null, 2));
Upvotes: 2