如何编辑.json对象的值

发布于 2025-01-17 19:39:17 字数 704 浏览 1 评论 0原文

我正在尝试在 .JSON 文件中创建一些简单的统计信息,我想对发出的每个命令进行计数,但我无法在 .JSON 文件中保存增量值。

.JSON

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

代码:

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')

.JSON 文件中的命令计数没有增加。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如何视而不见 2025-01-24 19:39:17

我注意到有几件事。您有一些不使用的VAR,并且您试图“增加”的内容是JSON文件中的一个字符串(已更新)。尝试一下。

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

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
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文