【问题标题】:Add new property to JSON file key using NodeJS使用 NodeJS 向 JSON 文件键添加新属性
【发布时间】:2020-04-22 20:01:08
【问题描述】:

抱歉,我还是编程新手,所以请原谅我,我需要帮助在 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"
  }
}

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

【问题讨论】:

    标签: javascript node.js json discord.js


    【解决方案1】:

    这应该可以工作

    var file = require('../../data/animals.json');
    const fs = require("fs");
    
    file.wolf.gender = "female";
    
    fs.writeFileSync("../../data/animals.json", JSON.stringify(file));
    

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

    【讨论】:

    • 您能否更新您的问题以添加此要求?您需要使用fs 覆盖json 文件。让我看看我是否可以更新我的答案。
    猜你喜欢
    • 1970-01-01
    • 2018-08-19
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2010-10-18
    • 2017-02-10
    相关资源
    最近更新 更多