我正在尝试将成员数据保存为JSON,但它无法正常工作。我正在使用discord.js框架。
我搜索过Stack Overflow和许多其他网站,但我找不到解决方案。
以下是代码段:
const user = message.guild.members.get(message.mentions.users.first().id);
const file = (user.id + ".json");
const content = {
"name": user.username,
"isFlagged": false,
"punishments": 1,
"id": user.id,
"discrim": user.discriminator
};
var B = content.toString();
fs.writeFileIfNotExist(file, B, function(err, existed) {
if (err) {
console.log(err)
} else {
console.log('file created sucessfuly!')
}
});
let points = JSON.parse(fs.readFileSync('./' + user.id + '.json'));
points.isFlagged = false;
points.punishments = points.punishments + 1;
答案 0 :(得分:0)
正如,CRice指出的那样,对一个从文字创建的对象调用Object.prototype.toString
,而不是使用返回JSON格式字符串的实现隐藏toString
,将返回字符串"[object Object"]
你想要什么。
以下代码段演示了这一点:
const content = {
name: 'John Smith',
isFlagged: false,
punishments: 1,
id: 5,
discrim: Symbol()
};
const b = content.toString();
console.log(b);

首先,按如下方式更改您的代码
const content = {
name: 'John Smith',
isFlagged: false,
punishments: 1,
id: 5,
discrim: Symbol()
};
const b = JSON.stringify(content);
console.log(b);

最后,考虑重新编写程序以干净利落地持续利用异步IO并改进命名模式以遵循既定的JavaScript约定。
const promisify = require('util.promisify');
const fs = require('fs');
const exists = promisify(fs.exists);
const writeFile = promisify(fs.writeFile);
const readFile = promisify(fs.readFile);
const user = message.guild.members.get(message.mentions.users.first().id);
const file = `${user.id}.json`;
const content = {
name: user.username,
isFlagged: false,
punishments: 1,
id: user.id,
discrim: user.discriminator
};
const b = JSON.stringify(content);
(async function () {
try {
await writeFileIfNotExist(file, b);
console.log('file created sucessfuly!')
} catch (e) {
console.error(e);
}
const json = await readFile(`./${user.id}.json`);
const user = JSON.parse(json);
user.isFlagged = false;
user.punishments = user.punishments + 1;
}());
async function writeFileIfNotExists(fileName, data) {
if (await exists(fileName)) {
return;
}
try {
await writeFile(fileName, data);
} catch (e) {
console.error(e);
}
}