0

Am trying to update the key, value pair of a JSON file in protractor nodejs.Am unable to pass the 'key' param to the left-hand side of the 'equal to' operator in order to update the value in JSON file. Please find the below code and help me in resolving this :

Calling Method :

this.test = async function () {
await writeToJSON(title, test-name-07282020-1234);
}

Method:

async function writeToJSON(key, value) {

  const { readFile, writeFile } = require('fs').promises;
  const jsonFilePath = `${__dirname}/testdata.json`;
  let data = JSON.parse(await readFile(jsonFilePath));

  data.LANG.TEST2.Default.key = value;  // line 5 ..due to key is not read from
  // the parameter passed in the method. It is trying to look the field 'key' in 
  //json file to update the value.

  writeFile(jsonFilePath, JSON.stringify(data, 2, 2)).then(() => {
    console.log('Finished writing to json file')
  })
}

testdata.json:

    {
  "LANG": {
    "TEST1": {
      "Default": {
        "username": "value1",
          "password": "value2"
      }
    },
    "TEST2": {
      "Default": {
        "username": "value1",
          "password": "value2",
            "title": "test-name-05252020-4786"

      }
    }

  }

It's failing at line 5

I want the key to read as 'title' and assign it the value 'test-name-07282020-1234'.Please help here!

Rahul
  • 759
  • 3
  • 21
  • 43
  • 1
    Check: ["Bracket notation"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#Bracket_notation) – Yoshi Jul 28 '20 at 10:15
  • Does this answer your question? [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – VLAZ Jul 28 '20 at 10:15
  • 1. You need `data.LANG.TEST2.Default[key] = value;` 2. You should surround the value in quotes, if you want a string `writeToJSON(title, "test-name-07282020-1234");` – VLAZ Jul 28 '20 at 10:16
  • Also relevant: [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/q/695050) | [Dynamically access object property using variable](https://stackoverflow.com/q/4244896) | [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/q/4968406) – VLAZ Jul 28 '20 at 10:19

1 Answers1

0

you have to access with the brackets notation, it perfectly match for your use case:

data.LANG.TEST2.Default[key] = value;
penguintheorem
  • 321
  • 1
  • 4