Pulkit Mehta
Pulkit Mehta

Reputation: 117

NodeJS script to modify a JSON file

I need to write a NodeJS script for the following task:

I have a temp.json file with content like:

{
  "name": "foo",
  "id": "1.2.15"
}

When we run the script, I want the temp.json files content changed. Specifically, I want the number after the 2nd decimal in id to be incremented as follows:

{
  "name": "foo",
  "id": "1.2.16"
}

I don't know JavaScript and would appreciate any help.

Thanks!

Upvotes: 3

Views: 9142

Answers (2)

niry
niry

Reputation: 3308

"use strict";

const fs = require('fs');

const data = JSON.parse(fs.readFileSync("file.json"));
const nums = data.id.split('.');
++nums[2];
data.id = nums.join('.');

fs.writeFileSync("file.json", JSON.stringify(data, null, 4));

Upvotes: 3

Paul
Paul

Reputation: 36319

And if you want to do it without breaking the async nature of Node, you can do it with the async functions as well:

const fs = require('fs');

fs.readFile('temp.json', 'utf8', (e, data) => {
  const obj = JSON.parse(data);
  const idParts = obj.id.split('.').map((el) => parseInt(el, 10))
  idParts[2] = idParts[2] + 1;
  obj.id = idParts.join('.');
  fs.writeFile('out.json', JSON.stringify(obj), (err) => {
     console.log(err || 'complete');
  });
});

Upvotes: 0

Related Questions