简体   繁体   English

我如何将键:值对添加到 node.js 中的 json 列表中?

[英]How would i add a key:value pair to a json list in node.js?

I am using node.js, and i want to add the arguments from a command and the server id as a key:value pair into a json file like this:我正在使用 node.js,我想将命令中的 arguments 和服务器 ID 作为键:值对添加到 json 文件中,如下所示:

{

    "guildid": "args",
    "guildid2": "args2",

}

And the current code that i have is far from what i want, where this code:我拥有的当前代码远非我想要的,这里代码:

const command = args.shift().toLowerCase();
const args = message.content.slice(config.prefix.length).trim().split(' ');

if (command === 'setup') {
const guildid = message.guild.id
        const data = { 
            [guildid]: `${args}`
            }
        const groupname = JSON.stringify(data, null, 2);
        fs.writeFile('./groups.json', groupname,{flags: "a"}, finished);
        function finished(err) {
            message.channel.send(`Success! Your group, **${args}**, has been registered to **${message.guild.name}**`
            )}

Outputs what i want to the json file, but if i run the command again it just appends to the end:输出我想要的 json 文件,但如果我再次运行该命令,它只会附加到末尾:

{
  "guildid": "args"
}{
  "guildid2": "args2"
}

I understand now that using the a flag just appends to the end no matter what and const data is what is giving it the brackets, but i want to know how to be able to format it in the way i showed at the beginning.我现在明白,无论如何使用 a 标志只会附加到末尾,而 const 数据是给它括号的东西,但我想知道如何能够以我在开头显示的方式对其进行格式化。 Apologies for any glaring errors i have made, this is one of my first times using javascript and node.js.对我犯的任何明显错误表示歉意,这是我第一次使用 javascript 和 node.js。

You'll have to get the original file first using fs.readFile[Sync] and JSON.parse , and then add on the property as you would any other object:您必须首先使用fs.readFile[Sync]JSON.parse获取原始文件,然后像添加任何其他 object 一样添加属性:

obj.key = 'value';

// or in your case:
obj[key_variable] = 'value';

You should also omit the 'a' flag as it will append another object (resulting in a syntax error) instead of modifying the one already there.您还应该省略'a'标志,因为它将 append 另一个 object (导致语法错误)而不是修改已经存在的那个。 Your code should look like this:您的代码应如下所示:

const guildid = message.guild.id;
const data = JSON.parse(fs.readFileSync('/groups.json'));

/* 
  You could either use:
  data[guildid] = `${args}`;

  OR, when stringifying to the file:
  const groupname = JSON.stringify({ 
    ...data, 
    [guildid]: `${args}` 
  }, null, 2);

  Either way will work
*/ 

data[guildid] = `${args}`;
const groupname = JSON.stringify(data, null, 2);

// remove { flags: 'a' }
fs.writeFile('./groups.json', groupname, finished);

// you should probably write some error handling
function finished(err) {
 message.channel.send(
  `Success! Your group, **${args}**, has been registered to **${message.guild.name}**`
 );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM