PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 7, 2022

[FIXED] how to edit value of the .JSON object

 October 07, 2022     counter, fs, json, node.js, statistics     No comments   

Issue

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


Answered By - PCDSandwichMan
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing