首页 > 解决方案 > 如何将数据推送到 JSON 文件中的数组并保存?

问题描述

所以我试图将一个数组推送到一个已经是数组格式的 JSON 文件中。

The code im using to attempt this is:

needle.get("https://bpa.st/raw/VHVQ", function(response, body){
     let testlist = require('../testlist.json') 
     let list = response.body;
     let listarray = list.split("\r\n")
     for (var i of listarray) {
     testlist.push(i);
     }

当我的应用程序运行时,它将 testlist.json 显示为:

["1", "2", "this", "is", "an", "example", "for", "stackoverflow"]

现在它似乎工作正常,它就像它更新了数组一样,但是如果我检查它,它没有,如果我重新启动我的应用程序,那么它会重置为原始的未编辑版本。

testlist.json looks like this:

["1", "2"]

之后,我试图让它编辑 json 文件看起来像这样:

["1", "2", "this", "is", "an", "example", "for", "stackoverflow"]

标签: node.jsarraysjsonnpmnode-modules

解决方案


当您使用 将 的内容testlist.json导入变量testlistrequire(),您正在将文件的内容加载到内存中。testlist如果您希望您的修改保持不变,您需要在对变量进行更改后写回文件。否则,您所做的更改将在程序进程退出时丢失。

您可以使用模块中的writeFileSync()方法fs以及JSON.stringify(),将其写testlisttestlist.json文件中:

const fs = require("fs");

let testlist = require("../testlist.json");

// Your code where you modify testlist goes here

// Convert testlist to a JSON string
const testlistJson = JSON.stringify(testlist);
// Write testlist back to the file
fs.writeFileSync("../testlist.json", testlistJson, "utf8");

编辑:您还应该使用该readFileSync()方法(也来自fs模块),并JSON.parse()执行 JSON 文件的初始读取,而不是require().

// This line
let testlist = require("../testlist.json");

// Gets replaced with this line
let testlist = JSON.parse(fs.readFileSync("../testlist.json", "utf8"));

您必须使用JSON.parseas ,fs.readFileSync因为当您读取文件时,它被读取为字符串,而不是 JSON 对象。


推荐阅读