Anna K
Anna K

Reputation: 1774

How to update json entry in node.js

How can I update json value with node.js? I found in internet couple examples but my is a little bit more complicated

I can open value I want to change

var contents = fs.readFileSync("./../../skill.json");
var jsonContent = JSON.parse(contents);
console.log("Address", jsonContent['manifest']['apis']['custom']['endpoint']['uri']);

but how to edit it with my value?

Upvotes: 0

Views: 691

Answers (3)

aymericbeaumet
aymericbeaumet

Reputation: 7332

Hence, modifying the content is as straightforward as

jsonContent['manifest']['apis']['custom']['endpoint']['uri'] = 'value';

Or even:

jsonContent.manifest.apis.custom.endpoint.uri = 'value';

That being said, I would suggest to at least wrap the assignment in a try catch block so that you are not exposed to a crash if the object does not deeply match the structure you expect to receive.

A more robust and versatile solution would be to leverage Lodash.set. For example:

_.set(jsonContent, ['manifest', 'apis', 'custom', 'endpoint', 'uri'], 'value');

As noted by @Patrick Roberts, modern JavaScript will allow leveraging the optional chaining operator ?.. This is currently only available in stage 1.

jsonContent?.manifest?.apis?.custom?.endpoint?.uri = 'value';

Upvotes: 1

аlex
аlex

Reputation: 5698

const {promisify} = require('util');
const fs = require('fs');
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);


(async (){

    try {
      var contents = await readFile("./../../skill.json");
      var jsonContent = JSON.parse(contents);
      console.log("Address", jsonContent.manifest.apis.custom.endpoint.uri);

      // modify your value
      jsonContent.manifest.apis.custom.endpoint.uri = 'new value';

       // stringify it and write to file
       await writeFile("./../../skill.json", JSON.stringify(jsonContent));

    } catch (e){
       console.error(e);
    }

})();

Upvotes: 0

ponury-kostek
ponury-kostek

Reputation: 8060

var contents = fs.readFileSync("./../../skill.json");
var jsonContent = JSON.parse(contents);
console.log("Address", jsonContent['manifest']['apis']['custom']['endpoint']['uri']);
// modify your value
jsonContent['manifest']['apis']['custom']['endpoint']['uri'] = 'new value';
// stringify it and write to file
fs.writeFileSync("./../../skill.json", JSON.stringify(jsonContent));

Upvotes: 1

Related Questions