1

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?

Sandra Schlichting
  • 25,050
  • 33
  • 110
  • 162
  • 2
    Does this answer your question? [JavaScript: Object Rename Key](https://stackoverflow.com/questions/4647817/javascript-object-rename-key) – Heretic Monkey Jul 01 '21 at 12:45
  • 3
    Personally, I like [this answer](https://stackoverflow.com/a/58974459/215552) the best, as it is more like your attempt. – Heretic Monkey Jul 01 '21 at 12:48

1 Answers1

2

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));
Ameer
  • 1,980
  • 1
  • 12
  • 24
  • 1
    This could overwrite existing keys assuming the following object: `{'a':'b', '"a"':'c'}` – niry Jul 01 '21 at 14:11