javascript - 从以下元素写入 JSON 文件夹
问题描述
我想知道如何读取/写入json
文件。
const Discord = require ('discord.js');
const client = new Discord.Client();
const {prefix, token,} = require('./config.json');
const fs = require ('fs');
client.login(token)
client.on('message', message => {
if(message.content.startsWith(prefix + "TC")) { //TC = team create
var args = message.content.split(' ').join(' ').slice(4);
if(!args) return message.channel.send("No")
var TeamCreate = `{"NameTeam": "${args}", "ManagerTeam": ${message.author.id}}`
fs.writeFile("./team.json", TeamCreate, (x) => {
if (x) console.error(x)
})}});
该json
文件将显示:
{"NameTeam": "teste","ManagerTeam": 481117441955463169}
我希望每次我们下订单时,它都会被添加到json
文件中。
例子:
1 first order = {"NameTeam": "teste","ManagerTeam": 481117441955463169}
2 second order = {"NameTeam": "teste","ManagerTeam": 481117441955463169}, {"NameTeam": "teste2","ManagerTeam": 1234567890}
解决方案
据我了解,您想制作一个json
包含团队列表的文件。
最简单的方法是读取和解析 json,对其进行更改,然后对 json 进行字符串化并更新文件。另外,用字符串制作 json 真的很麻烦,可能会导致语法错误,而在 javascript 中将 js 对象转换为 json 就像这样做一样简单JSON.stringify(javascriptObject)
尝试这样的事情:
const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token, } = require('./config.json');
const fs = require('fs');
client.login(token)
client.on('message', message => {
if (message.content.startsWith(prefix + "TC")) { //TC = team create
var args = message.content.split(' ').join(' ').slice(4);
if (!args) return message.channel.send("No")
var team = {
NameTeam: args,
ManagerTeam: message.author.id
}
fs.readFile("./team.json", (err, data) => {
if (!err && data) {
var parsedJson;
try {
parsedJson = JSON.parse(data);
//Make sure the parsedJson is an array
if (!(parsedJson instanceof Array)) {
parsedJson = [];
}
}
catch (e) {
console.log("Couldn't parse json.");
parsedJson = [];
}
finally {
//Add the newly created team to parsedJson
parsedJson.push(team);
//Write file, stringifying the json.
fs.writeFile("./team.json", JSON.stringify(parsedJson), (err) => {
if (!err) {
console.log("Successfully created team.");
}
else {
console.log("Error writing to file.")
}
});
}
}
else {
console.log("Error reading json");
}
});
}
});
希望这会有所帮助,祝你好运。
推荐阅读
- python - pytest requests_mock 不适用于产量
- java - OSGI - 如何解决:ClassNotFoundException?(org.eclipse.osgi.internal.loader.BundleLoader.findClass)
- java - 地图不包含使用 put 方法 java 存储的密钥
- python - 双星号 (**) 运算符给出不同的结果
- http-status-code-404 - 如何设置条件以测试网页的 HTTP 状态码 403、404、500、503
- javascript - 在javascript中获取元素值返回null
- sql - 夏令时导致数据库中的日期不正确
- php - 在同一页面重定向并向用户显示消息
- python - TypeError: height_rb() 接受 2 个位置参数,但给出了 3 个
- azure-devops - Devops 管道没有启动日志记录,因为它没有触发“dotnet appname.dll”