最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NodeJS script to modify a JSON file - Stack Overflow

programmeradmin0浏览0评论

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!

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!

Share Improve this question edited Aug 18, 2021 at 6:53 niry 3,30825 silver badges37 bronze badges asked Nov 1, 2018 at 5:53 Pulkit MehtaPulkit Mehta 1172 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3
"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));

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 || 'plete');
  });
});
发布评论

评论列表(0)

  1. 暂无评论