[提交数据Express时追加多个JSON条目
目标:
当我提交JSON数据时,无论我提交多少条目,我都希望数据到达JSON文件时能正确格式化。
问题:
到目前为止,当我提交数据时,它没有正确地附加到JSON文件中;例如,它像这样追加:
{
"name": "Jay Money",
"photo": "/photo/url",
"scores": [
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5"
]
}{
"name": "Jay Money",
"photo": "/photo/url",
"scores": [
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5"
]
}
我希望在我追加提交时看起来像这样:
[{
"name": "Jay Money",
"photo": "/photo/url",
"scores": [
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5"
]
},
{
"name": "Jay Money",
"photo": "/photo/url",
"scores": [
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5"
]
}]
我仍在研究,但没有运气,我只是在寻找指导。
这是我的server.js文件的样子:
// Dependencies
let express = require("express");
let bodyParser = require("body-parser");
let path = require("path");
let fs = require("fs");
// Set the port of our application
// process.env.PORT lets the port be set by Heroku
let PORT = process.env.PORT || 4000;
// Create express app instance.
let app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
// TODO Add your routes here
app.get('/', function(req,res){
res.sendFile('home.html', {root : __dirname + '/app/public'});
});
app.get('/survey', function(req, res){
res.sendFile('survey.html',{root : __dirname + '/app/public'} )
});
app.post('/surveyResponse', function(req,res){
let photo = req.body.url;
let name = req.body.name;
let travel = req.body.travel;
let affection = req.body.affection;
let family = req.body.family;
let fitness = req.body.fitness;
let movie = req.body.movie;
let education = req.body.education;
let career = req.body.career;
let marriage = req.body.marriage;
let children = req.body.children;
let pets = req.body.pets;
let sum = 0;
let person = {
name: name,
photo: photo,
scores: [
travel,
affection,
family,
fitness,
movie,
education,
career,
marriage,
children,
pets
]
}
let data = JSON.stringify(person, null ,2);
fs.appendFileSync('./app/data/friends.json', data);
//finding the sum of all the numbers
for(i in person.scores){
sum+=Number(person.scores[i]);
}
//------------------------------------
res.send('Your name is ' + name + ' and your score is ' + sum );
});
// Start our server so that it can begin listening to client requests.
app.listen(PORT, function() {
// Log (server-side) when our server has started
console.log("Server listening on: http://localhost:" + PORT);
});
这是我用来附加的代码:
let data = JSON.stringify(person, null ,2);
fs.appendFileSync('./app/data/friends.json', data);
编辑:
我知道How to append JSON data to existing JSON file node.js,它不能解决我的问题。当我尝试将代码合并到我的代码中时:
var data = fs.readFileSync('friends.json');
var json = JSON.parse(data);
json.push(...person);
fs.writeFile("friends.json", JSON.stringify(json))
我一直收到以下错误消息:
SyntaxError:JSON输入意外结束
所以我尝试了一个新的变化,该变化从...
中删除了json.push
,因此它看起来像是json.push(person)
。
但是我一直收到相同的错误消息。我假设是因为我的文件为空,这会导致错误。我假设我必须先编写代码,然后再执行下一步。
更新
我发现我觉得自己正处于正确的轨道(Save html-form data in json format in a .json file using node and express with javascript )上,我似乎无法将其集成到我的代码中。我无法弄清楚为什么总是出现以下错误:
SyntaxError:JSON输入意外结束在JSON.parse()在fs.readFile(server.js:86:39)在FSReqWrap.readFileAfterClose [完成时](fs.js:511:3)
这是我正在使用的新代码:
// 1. Read the existing file
fs.readFile('./app/data/friends.json', (err, data) => {
if (err && err.code === "ENOENT") {
// But the file might not yet exist. If so, just write the object and bail
return fs.writeFile('./app/data/friends.json', JSON.stringify(person), error => console.error);
} else if (err) {
// Some other error
console.error(err);
}
// 2. Otherwise, get its JSON content
else {
try {
const fileData = JSON.parse(data);
// 3. Append the object you want
fileData.push(person);
//4. Write the file back out
return fs.writeFile('./app/data/friends.json', JSON.stringify(fileData), error => console.error)
} catch (exception) {
console.error(exception);
}
}
});
回答如下:[基本上,我必须重写该函数并创建一个接受所提交信息的newFriend。然后,提交的信息将被推送到当前JSON对象中,然后加入。
let newFriend = req.body; //STORING INCOMING JSON
// PUSHING NEW MATCH INTO JSON
friendsJSON.push(newFriend);
fs.writeFile(path.join(__dirname + '/../data', 'friends.json'), JSON.stringify(friendsJSON, null, 2), function(err){
if (err) throw err;
})
[提交数据Express时追加多个JSON条目
目标:
当我提交JSON数据时,无论我提交多少条目,我都希望数据到达JSON文件时能正确格式化。
问题:
到目前为止,当我提交数据时,它没有正确地附加到JSON文件中;例如,它像这样追加:
{
"name": "Jay Money",
"photo": "/photo/url",
"scores": [
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5"
]
}{
"name": "Jay Money",
"photo": "/photo/url",
"scores": [
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5"
]
}
我希望在我追加提交时看起来像这样:
[{
"name": "Jay Money",
"photo": "/photo/url",
"scores": [
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5"
]
},
{
"name": "Jay Money",
"photo": "/photo/url",
"scores": [
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5",
"5"
]
}]
我仍在研究,但没有运气,我只是在寻找指导。
这是我的server.js文件的样子:
// Dependencies
let express = require("express");
let bodyParser = require("body-parser");
let path = require("path");
let fs = require("fs");
// Set the port of our application
// process.env.PORT lets the port be set by Heroku
let PORT = process.env.PORT || 4000;
// Create express app instance.
let app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
// TODO Add your routes here
app.get('/', function(req,res){
res.sendFile('home.html', {root : __dirname + '/app/public'});
});
app.get('/survey', function(req, res){
res.sendFile('survey.html',{root : __dirname + '/app/public'} )
});
app.post('/surveyResponse', function(req,res){
let photo = req.body.url;
let name = req.body.name;
let travel = req.body.travel;
let affection = req.body.affection;
let family = req.body.family;
let fitness = req.body.fitness;
let movie = req.body.movie;
let education = req.body.education;
let career = req.body.career;
let marriage = req.body.marriage;
let children = req.body.children;
let pets = req.body.pets;
let sum = 0;
let person = {
name: name,
photo: photo,
scores: [
travel,
affection,
family,
fitness,
movie,
education,
career,
marriage,
children,
pets
]
}
let data = JSON.stringify(person, null ,2);
fs.appendFileSync('./app/data/friends.json', data);
//finding the sum of all the numbers
for(i in person.scores){
sum+=Number(person.scores[i]);
}
//------------------------------------
res.send('Your name is ' + name + ' and your score is ' + sum );
});
// Start our server so that it can begin listening to client requests.
app.listen(PORT, function() {
// Log (server-side) when our server has started
console.log("Server listening on: http://localhost:" + PORT);
});
这是我用来附加的代码:
let data = JSON.stringify(person, null ,2);
fs.appendFileSync('./app/data/friends.json', data);
编辑:
我知道How to append JSON data to existing JSON file node.js,它不能解决我的问题。当我尝试将代码合并到我的代码中时:
var data = fs.readFileSync('friends.json');
var json = JSON.parse(data);
json.push(...person);
fs.writeFile("friends.json", JSON.stringify(json))
我一直收到以下错误消息:
SyntaxError:JSON输入意外结束
所以我尝试了一个新的变化,该变化从...
中删除了json.push
,因此它看起来像是json.push(person)
。
但是我一直收到相同的错误消息。我假设是因为我的文件为空,这会导致错误。我假设我必须先编写代码,然后再执行下一步。
更新
我发现我觉得自己正处于正确的轨道(Save html-form data in json format in a .json file using node and express with javascript )上,我似乎无法将其集成到我的代码中。我无法弄清楚为什么总是出现以下错误:
SyntaxError:JSON输入意外结束在JSON.parse()在fs.readFile(server.js:86:39)在FSReqWrap.readFileAfterClose [完成时](fs.js:511:3)
这是我正在使用的新代码:
// 1. Read the existing file
fs.readFile('./app/data/friends.json', (err, data) => {
if (err && err.code === "ENOENT") {
// But the file might not yet exist. If so, just write the object and bail
return fs.writeFile('./app/data/friends.json', JSON.stringify(person), error => console.error);
} else if (err) {
// Some other error
console.error(err);
}
// 2. Otherwise, get its JSON content
else {
try {
const fileData = JSON.parse(data);
// 3. Append the object you want
fileData.push(person);
//4. Write the file back out
return fs.writeFile('./app/data/friends.json', JSON.stringify(fileData), error => console.error)
} catch (exception) {
console.error(exception);
}
}
});
回答如下:[基本上,我必须重写该函数并创建一个接受所提交信息的newFriend。然后,提交的信息将被推送到当前JSON对象中,然后加入。
let newFriend = req.body; //STORING INCOMING JSON
// PUSHING NEW MATCH INTO JSON
friendsJSON.push(newFriend);
fs.writeFile(path.join(__dirname + '/../data', 'friends.json'), JSON.stringify(friendsJSON, null, 2), function(err){
if (err) throw err;
})