Sandra Schlichting
Sandra Schlichting

Reputation: 25996

How to update JSON keys in place?

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

Answers (1)

Ameer
Ameer

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

Related Questions