javascript - 使用 NodeJS 向 JSON 文件键添加新属性

标签 javascript node.js json discord.js

抱歉,我还是编程新手,所以请原谅我,我需要帮助在 JSON 文件中添加新属性。 :(

我想让它编辑 JSON文件~!喵~

animals.json:(添加新属性之前)

{
  "cat": {
    "name": "Hiro",
    "age": 6
  },
  "wolf": {
    "name": "Kairo",
    "age": 3
  }
}

index.js(添加新属性的示例代码)

var file = require('../../data/animals.json');

file["wolf"].push({gender: "female"})

运行 index.js 后的新 animals.json

{
  "cat": {
    "name": "Hiro",
    "age": 6
  },
  "wolf": {
    "name": "Kairo",
    "age": 3,
    "gender": "female"
  }
}

这可能吗?如果是这样,怎么办?谢谢!

最佳答案

这应该可以工作

var file = require('../../data/animals.json');
const fs = require("fs");

file.wolf.gender = "female";

fs.writeFileSync("../../data/animals.json", JSON.stringify(file));

使用点表示法,您可以在非空属性上创建或更新属性。

关于javascript - 使用 NodeJS 向 JSON 文件键添加新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59592404/

相关文章:

javascript - 有没有办法让 child 从 jquery 中的某个索引到某个索引

node.js - 验证可能不存在的字段上的 $regex

c# - 如何使用 JSON.NET 保存具有四个空格缩进的 JSON 文件?

json - 尼菲 : Extract Content of FlowFile and Add that Content to the Attributes

java - Spring Batch - 从 Reader 和 JSON 解析中删除某些类型的行

javascript - Vue.js 服务器端渲染 : document is not defined

javascript - 如何在输入元素文本字段中显示特殊字符但仍保留 JQuery 中的值

javascript - Hammer.js:单击 SVG 元素以启动 javascript 在 iPhone Safari 中不起作用

node.js - Mongoose model.save() 卡在等待状态?

Node.JS:重用套接字?