在使用NodeJS向JSON文件中添加新的键值对时,可以采用以下方法:

huangapple go评论98阅读模式
英文:

Adding a new key value inside a JSON file using NodeJS

问题

以下是我试图在我的JavaScript文件中执行的操作:

const file = require('../../data/files.json');
var data = {
  "wolf": {"nani": "awoo"},
  "loli": {"nani": "kimochi"}
}

file.push(data);

我的当前.json文件内容:

{
  "cat" : {
    "nani": "meow"
  },
  "dog": {
    "nani": "woof"
  }
}

这是我希望在使用NodeJS写入JSON文件后我的.json文件看起来的样子:

{
  "cat" : {
    "nani": "meow"
  },
  "dog": {
    "nani": "woof"
  },
  "wolf": {
    "nani": "awoo"
  },
  "loli": {
    "nani": "kimochi"
  }
}

这是可能的吗?如果可以的话,谢谢!

英文:

Here is what I'm trying to do in my Javascript File:

const file = require('../../data/files.json');
var data = {
  "wolf": {"nani": "awoo"},
  "loli": {"nani": "kimochi"}
}

file.push(data);

My current .json file contents:

{
  "cat" : {
    "nani": "meow"
  },
  "dog": {
    "nani": "woof"
  }
}

Here's kind of what I want my .json file to be after writing to the JSON file using NodeJS:

{
  "cat" : {
    "nani": "meow"
  },
  "dog": {
     "nani": "woof"
  },
  "wolf": {
    "nani": "awoo"
  },
  "loli": {
    "nani": "kimochi"
  }
}

Is this possible? If so thank you~!

答案1

得分: 2

当然,在运行时修改JSON是可能的。但是,您当前的方法存在三个问题。

  1. file.push(data) - .push() 是一个数组的方法,但 file 不是一个数组,而是一个对象。您可以使用类似 Object.assign(file, data) 的方法将 data 中的所有属性分配给 file

  2. 您的 data 的格式与您想要的JSON结果格式不同。例如,代替 "wolf": "awoo",它需要是 "wolf": { "nani": "awoo" }。您可以保持当前格式,但必须转换数据以使其符合所需的结果格式。

  3. 以这种方式修改JSON只会修改在使用 require() 读取时存储在内存中的JSON的副本。您仍然需要保存此修改后的JSON副本。就像在文本编辑器中,您的更改只有在点击保存按钮后才会保存。要执行此操作,您可以使用 fs.writeFileJSON.stringify

// 导入标准文件系统模块以读取/写入文件和文件夹
const fs = require("fs");

// 在修改数据后,使用以下方法保存更改
fs.writeFile("../../data/files.json", JSON.stringify(file), err => {
    if (err) console.log(err);
});

需要使用 JSON.stringify,因为 const file = require(...); 会将JSON转换为JavaScript对象。JSON只是文本,而JavaScript对象是一个具有原型和属性等内容的内存数据结构。JSON.stringify 将其转换回文本,以便您可以保存对象的文本版本。


与您的问题无关,但我看到您正在使用discord.js,所以这可能是为了一个discord机器人。如果您计划使用命令修改此JSON,请注意,如果您的机器人被添加到许多服务器,JSON存储将变得非常不稳定,未来可能会丢失/损坏数据。这可能会出现许多原因,但因为每次更改数据都需要对文件进行完整的重写,如果在重写过程中发生故障,它就会处于损坏状态。

我强烈建议使用适当的数据库解决方案来存储动态数据,如PostgreSQL、Redis或任何其他SQL/NoSQL解决方案。

英文:

Yes, of course it's possible to modify JSON at runtime. However there are three problems with your current approach.

  1. file.push(data) - .push() is a function on Arrays. However, file is not an array, it is an object. You can use something like Object.assign(file, data) to assign all the properties from data to file instead.

  2. Your data is in a different format than how you want your JSON result to look like. Instead of "wolf": "awoo" it needs to be "wolf": { "nani": "awoo" }, for example. You could keep it in the current format but you'd have to transform the data to get it in the right result format.

  3. Modifying the JSON this way only modifies the copy of the JSON held in memory when it's read by require(). You still need to save this modified copy of the JSON. Just like in a text editor where your changes aren't saved until you hit the save button. To do this you can use fs.writeFile and JSON.stringify:

     //import the standard filesystem module to read/write files and folders
     const fs = require("fs"); 
    
     //after you modify your data use this to save the changes
     fs.writeFile("../../data/files.json", JSON.stringify(file), err => {
         if(err) console.log(err);
     });
    

JSON.stringify is needed because const file = require(...); will convert the JSON to a JavaScript object. JSON is just text, a JS object is an in-memory data structure that has a prototype and properties and such things. JSON.stringify converts it back to text so you can just save the text version of the object.


Unrelated to your question, but I see you're using discord.js, so this is probably for a discord bot. If you plan on modifying this JSON with a command, be wary that if your bot gets added to many servers, JSON storage gets very unstable and is likely in the future to lose/corrupt the data. This can happen for many reasons, but it's because every time you change the data it requires a full rewrite of the file, and if the process fails during the rewrite it is left in a corrupted state.

I strongly recommend using a proper database solution to store dynamic data, like postgres, redis, or any other SQL/NoSQL solution.

答案2

得分: 1

你可以尝试像这样操作

let file = require('../../data/files.json');
console.log(file);

// 要在任何对象中添加键值对,请像这样使用:-
// object['key'] = 'value'
file['wolf'] = {
    "nani": "awoo"
}
file['loli'] = {
    "nani": "kimochi"
}
console.log(file);
英文:

You can try like this

let file = require('../../data/files.json');
console.log(file);

// to add key value pair in any Object use like this :-
// object['key'] = 'value'
file['wolf'] = {
    "nani": "awoo"
}
file['loli'] = {
    "nani": "kimochi"
}
console.log(file);

答案3

得分: 0

你需要读取文件的内容,添加你的更改,然后再次写入文件。

你所做的会导致这样的结果:

{
  "cat": {
    "nani": "meow"
  },
  "dog": {
    "nani": "woof"
  }
}
{
  "wolf": {
    "nani": "awoo"
  },
  "loli": {
    "nani": "kimochi"
  }
}
你不能简单地追加到 JSON,你需要修改它。要修改它,你需要解析它。
英文:

You would have to read in the content of the file, add your changes and write out the file again.

What you did would result in this:

{
  "cat" : {
    "nani": "meow"
  },
  "dog": {
    "nani": "woof"
  }
}
{
  "wolf": {
    "nani": "awoo"
  },
  "loli": {
    "nani": "kimochi"
  }
}

You can't just append to JSON, you need to modify it. And to modify it you need to parse it.

huangapple
  • 本文由 发表于 2020年1月4日 00:57:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定