Home > OS >  how to edit value of the .JSON object
how to edit value of the .JSON object

Time:03-29

I'm trying to create some simple statistics in the .JSON file, I would like to count each command that was issued, but I'm unable to save increment value in the .JSON file.

.JSON

{
   "stats": {
      "value": 0,
      "points": 0,
      "commandUsed": 0
   }
}

code:

const fs = require('fs');

let statistics = fs.readFileSync(__dirname   '/stats.json', 'utf8');
let stats = JSON.parse(statistics)
console.log(stats)

//stats
let value = stats['stats']['value']
let points = stats['stats']['points']
let usedCommands = stats['stats']['commandUsed']


usedCommands   
console.log(usedCommands) //logs actual amount of issued commands
fs.writeFileSync(__dirname   '/stats.json', JSON.stringify(stats, 0, 4), 'utf8')

The command count is not increasing in the .JSON file.

CodePudding user response:

There are a couple of things I noticed. You had a few vars that you were not using and what you were trying to "increment" was a string in your JSON file (updated). Try this.

const fs = require("fs");

const statistics = fs.readFileSync(__dirname   "/stats.json", "utf8");
const { stats } = JSON.parse(statistics);

let commandUsed = stats["commandUsed"];
commandUsed  ;

const updatedStats = { stats: { ...stats, commandUsed } };

fs.writeFileSync(
  __dirname   "/stats.json",
  JSON.stringify(updatedStats, 0, 4),
  "utf8"
);
{
    "stats": {
        "commandUsed": 0,
        "points": 0,
        "value": 0
    }
}
  • Related