【问题标题】:Take JSON from a file, add a key to it. And then overwrite the file with the key in it从文件中获取 JSON,为其添加密钥。然后用其中的密钥覆盖文件
【发布时间】:2022-01-10 15:31:17
【问题描述】:

您好 Stack Overflow 用户/开发者,

我正在尝试使用 fs 模块从文件中获取 JSON,向保存 JSON 的变量添加一个键,然后覆盖文件。基本上是用 fs 制作一个数据保存系统。我尝试了许多不同的方法,但在尝试时遇到了错误。

SyntaxError: Unexpected End of JSON input

var UserTable = JSON.stringify(require('./data/Data'))
    UserTable[`User_${id[key]}`] = value;

    setTimeout(() => {
      console.log(UserTable);
    }, 1000);

    fs.writeFileSync(__dirname + '/data/Data.json', UserTable);

【问题讨论】:

  • 你在哪里得到错误?请粘贴json
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: javascript node.js json


【解决方案1】:

您在 JSON.stringfy() 之后更新 json。

abc.json 文件之前


{
   name : "Tom"
}

const appjson = require("./abc.json");
var fs = require('fs');

id = [1, 2, 3, 4] // json or array
key = 3 //index or key
value = "some_value" // data to set

appjson[`User_${id[key]}`] = value;

fs.writeFileSync(__dirname + '/abc.json', JSON.stringify(appjson));

在 abc.json 之后

{
    "name": "Tom",
    "User_4": "some_value"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    相关资源
    最近更新 更多