node.js - 如何将数据推送到 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"]
解决方案
当您使用 将 的内容testlist.json
导入变量testlist
时require()
,您正在将文件的内容加载到内存中。testlist
如果您希望您的修改保持不变,您需要在对变量进行更改后写回文件。否则,您所做的更改将在程序进程退出时丢失。
您可以使用模块中的writeFileSync()
方法fs
以及JSON.stringify()
,将其写testlist
回testlist.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.parse
as ,fs.readFileSync
因为当您读取文件时,它被读取为字符串,而不是 JSON 对象。
推荐阅读
- html - 如何防止我的网站布局被新的 CSS 动画代码输入弄乱?
- asp.net - SqlDataAdapter.Fill 运行 SQL 命令两次
- python-3.x - OSError:找不到 Python 库:libpython3.7.so.1.0、libpython3.7m.so.1.0
- arrays - 将两个数组相减,但一个会定期重复?
- wordpress - 页面部分顺序(Wordpress 管理中的动态选择)
- java - Springboot在实体存在上的预定触发器
- wordpress - WooCommerce 商店页面上没有“主要查询”
- ios - 在 SwiftUI Xcode 13 iOS15 中编辑时,内容未显示在 TextFields 中
- reactjs - NextJs 基于正则表达式的重定向
- r - 日期:尚未针对此非数字和非字符类型实现 NAbounds=TRUE