Search code examples
node.jsjsonstatisticscounterfs

how to edit value of the .JSON object


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.


Solution

  • 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
        }
    }