我有一个 json 文件,data.json
它有 3 个字段id, name and address
。我想在运行时通过一些函数使用 JS 在该文件中添加一个新对象。我怎样才能做到这一点?
假设你的文件有
{
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"
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句