-2

Say I have this code in node.js:

var fs = require("fs");
var file_content = fs.readFileSync('file.json');
var json = JSON.parse(file_content);

let x = "c";
json.x = 3;
fs.writeFileSync("file.json", JSON.stringify(json));

and this JSON file:

{"a":1,"b":2}

I want to create json object "c" but this code would create "x". How would I create "c" this way?

1 Answers1

0

You want to set the property c of the object json. The synthax json.x corresponds to the property x. You need to use square brackets if you want the value of x as property.

let x = 'c';
json[x] = 3;
L. Meyer
  • 2,863
  • 1
  • 23
  • 26