[英]How to push information in JSON?
I am a beginner.我是初学者。 I'd like to push data to JSON array file.
我想将数据推送到 JSON 数组文件。
In this case, I want to push this:在这种情况下,我想推动这个:
{
"name" : "name1",
"pass" : "password1"
},
This is index.js:这是 index.js:
var express = require('express');
var fs = require('fs'); // util to read file
var app = express();
app.get('/',function(req,res){
//code here
})
And this is data.json这是数据。json
[
//pushed data here
]
Read file:读取文件:
var fs = require('fs');
var array = JSON.parse(fs.readFileSync('data.json', 'utf8'));
Push data:推送数据:
array.push({
"name" : "name1",
"pass" : "password1"
})
Overwrite file:覆盖文件:
var jsonArray = JSON.stringify(array)
fs.writeFileSync(path,jsonArray,{encoding:'utf8',flag:'w'})
This is a rough idea of what you are asking for.这是您所要求的粗略概念。 What this chunk is doing is reading the data.json then Copying it to a new array where we can push/mutate data then re-writes the data.json with updatations
这个块正在做的是读取数据。json 然后将其复制到一个新数组中,我们可以在其中推送/变异数据,然后重新写入数据。json 与更新
var express = require('express');
var fs = require('fs'); // util to read file
var app = express();
app.get('/file', (req,res)=>{
fs.readFile('./data.json', 'utf-8',(err,data)=>{
data2 = JSON.parse(data);
dataNew = [...data2];
dataToPush = {"pass": "password"};
dataNew.push(dataToPush)
fs.writeFileSync('data.json', JSON.stringify(dataNew))
})
res.end();
}
This is data.json这是数据。json
[
//pushed data will come here
]
Try running this code first yourself to get a better idea then you can easily implement it.尝试自己先运行此代码以获得更好的想法,然后您可以轻松实现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.