Javascript 使用 Node.js 在 JSON 文件中写入/添加数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36856232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write / add data in JSON file using Node.js
提问by Isoftmaster
I am trying to write JSON file using node from loop data, e.g.:
我正在尝试使用循环数据中的节点编写 JSON 文件,例如:
let jsonFile = require('jsonfile');
for (i = 0; i < 11; i++) {
jsonFile.writeFile('loop.json', "id :" + i + " square :" + i * i);
}
outPut in loop.json is:
loop.json 中的输出是:
id :1 square : 1
but I want output file like this (below) and also if I run that code again it should add that new output as elements in same existing JSON file:
但我想要这样的输出文件(如下),并且如果我再次运行该代码,它应该将该新输出添加为同一个现有 JSON 文件中的元素:
{
"table":[
{
"Id ":1,
"square ":1
},
{
"Id ":2,
"square ":3
},
{
"Id ":3,
"square ":9
},
{
"Id ":4,
"square ":16
},
{
"Id ":5,
"square ":25
},
{
"Id ":6,
"square ":36
},
{
"Id ":7,
"square ":49
},
{
"Id ":8,
"square ":64
},
{
"Id ":9,
"square ":81
},
{
"Id ":10,
"square ":100
}
]
}
I want to use same file that I created 1st time but whenever I run that code new elements should add in that same file
我想使用我第一次创建的同一个文件,但是每当我运行该代码时,新元素都应该添加到同一个文件中
const fs = require('fs');
let obj = {
table: []
};
fs.exists('myjsonfile.json', function(exists) {
if (exists) {
console.log("yes file exists");
fs.readFile('myjsonfile.json', function readFileCallback(err, data) {
if (err) {
console.log(err);
} else {
obj = JSON.parse(data);
for (i = 0; i < 5; i++) {
obj.table.push({
id: i,
square: i * i
});
}
let json = JSON.stringify(obj);
fs.writeFile('myjsonfile.json', json);
}
});
} else {
console.log("file not exists");
for (i = 0; i < 5; i++) {
obj.table.push({
id: i,
square: i * i
});
}
let json = JSON.stringify(obj);
fs.writeFile('myjsonfile.json', json);
}
});
回答by kailniris
If this json file won't become too big over the time you should try:
如果这个 json 文件随着时间的推移不会变得太大,你应该尝试:
Create a javascript object with the table array in it
var obj = { table: [] };
Add some data to it like
obj.table.push({id: 1, square:2});
Convert it from an object to string with stringify
var json = JSON.stringify(obj);
use fs to write the file to disk
var fs = require('fs'); fs.writeFile('myjsonfile.json', json, 'utf8', callback);
if you want to append it read the json file and convert it back to an object
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){ if (err){ console.log(err); } else { obj = JSON.parse(data); //now it an object obj.table.push({id: 2, square:3}); //add some data json = JSON.stringify(obj); //convert it back to json fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back }});
创建一个包含表数组的 javascript 对象
var obj = { table: [] };
向其中添加一些数据,例如
obj.table.push({id: 1, square:2});
使用 stringify 将其从对象转换为字符串
var json = JSON.stringify(obj);
使用 fs 将文件写入磁盘
var fs = require('fs'); fs.writeFile('myjsonfile.json', json, 'utf8', callback);
如果要附加它,请读取 json 文件并将其转换回对象
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){ if (err){ console.log(err); } else { obj = JSON.parse(data); //now it an object obj.table.push({id: 2, square:3}); //add some data json = JSON.stringify(obj); //convert it back to json fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back }});
This will work for data big as 100 MB max effectively. Over this limit, you should use a database engine.
这将有效地适用于最大 100 MB 的数据。超过此限制,您应该使用数据库引擎。
UPDATE:
更新:
Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.
创建一个函数,以字符串形式返回当前日期(年+月+日)。创建名为此字符串 + .json 的文件。fs 模块有一个函数可以检查名为 fs.stat(path, callback) 的文件是否存在。有了这个,您可以检查文件是否存在。如果存在,则使用 read 函数,如果不存在,则使用 create 函数。使用日期字符串作为路径,因为文件将被命名为今天的日期 + .json。回调将包含一个 stats 对象,如果文件不存在,该对象将为 null。
回答by Jacob Nelson
Please try the following program. You might be expecting this output.
请尝试以下程序。您可能会期待此输出。
var fs = require('fs');
var data = {}
data.table = []
for (i=0; i <26 ; i++){
var obj = {
id: i,
square: i * i
}
data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
if (err) throw err;
console.log('complete');
}
);
Save this program in a javascript file, say, square.js.
将此程序保存在一个 javascript 文件中,例如 square.js。
Then run the program from command prompt using the command node square.js
然后使用命令从命令提示符运行程序 node square.js
What it does is, simply overwriting the existing file with new set of data, every time you execute the command.
它的作用是,每次执行命令时,只需用一组新数据覆盖现有文件。
Happy Coding.
快乐编码。
回答by Pankaj Chauhan
Above example is also correct, but i provide simple example:
上面的例子也是正确的,但我提供了一个简单的例子:
var fs = require("fs");
var sampleObject = {
name: 'pankaj',
member: 'stack',
type: {
x: 11,
y: 22
}
};
fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
if (err) {
console.error(err);
return;
};
console.log("File has been created");
});
回答by Zamboney
you should read the file, every time you want to add a new property to the json, and then add the the new properties
您应该阅读文件,每次要向 json 添加新属性时,然后添加新属性
var fs = require('fs');
fs.readFile('data.json',function(err,content){
if(err) throw err;
var parseJson = JSON.parse(content);
for (i=0; i <11 ; i++){
parseJson.table.push({id:i, square:i*i})
}
fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
if(err) throw err;
})
})
回答by Zamboney
try
尝试
var fs = require("fs");
var sampleObject = { your data };
fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
if (err) { console.error(err); return; };
console.log("File has been created");
});
回答by Nirojan Selvanathan
For synchronous approach
对于同步方法
const fs = require('fs')
fs.writeFileSync('file.json', JSON.stringify(jsonVariable));
回答by avck
For formatting jsonfile gives spaces
option which you can pass as a parameter:
对于格式化 jsonfile 提供了spaces
可以作为参数传递的选项:
jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
console.error(err);
})
Or use jsonfile.spaces = 4
. Read details here.
或使用jsonfile.spaces = 4
. 在此处阅读详细信息。
I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.
我不建议每次在循环中写入文件,而是在循环中构造 JSON 对象并在循环外写入文件。
var jsonfile = require('jsonfile');
var obj={
'table':[]
};
for (i=0; i <11 ; i++){
obj.table.push({"id":i,"square":i*i});
}
jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
console.log(err);
});