Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 596
Pulkit Mehta Avatar asked Dec 05 '25 22:12

Pulkit Mehta


1 Answers

"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));
like image 114
niry Avatar answered Dec 08 '25 11:12

niry