我有一个json文件data.json
,它具有3个字段id, name and address
。我想在运行时使用JS通过某个函数在该文件中添加一个新对象。我该怎么办?
答案 0 :(得分:0)
假设您的文件具有
{
id: 1,
name: "Binayak",
address: "stackoverflow"
}
您可以使用fs读写文件
const fs = require('fs');
let data = fs.readFileSync(filePath, "utf-8");
data = JSON.parse(data);
data.myKey = {
new: "object"
}
fs.writeFileSync(filePath, JSON.stringify(data));
会给予
{
id: 1,
name: "Binayak",
address: "stackoverflow",
myKey: {
new: "object"
}
}
答案 1 :(得分:0)
要实现此目的,您必须在node中打开文件,读取解析json内容,修改js变量,然后进行字符串化并保存结果。
这可能是您要查找的内容: const fs = require(“ fs”);
//Reads the file, and executes function on completion
fs.readFile("DIRECTORY_TO_FILE/data.json", "utf-8", (err, result) => {
if (err) throw err;
let data = JSON.parse(result);
//Modify your data object here
//Saves the file, make sure to provide the right directory
fs.writeFile(
"DIRECTORY_TO_FILE/data.json",
JSON.stringify(data),
"utf-8",
function(err) {
console.log("File saved successfuly!");
}
);
});