JavaScript:向现有的json文件添加一个发布请求jsonstring

我有一个简单的快速应用程序,需要一些JSON数据的发布请求。 我想采取这些数据,并将其附加到现有的json文件(如果存在)。 键值对可能不同。 我当前的版本将对象推到一个对象数组。 理想情况下,我想添加另一个键/值对:

app.post('/notes', function(req, res){ var body = ""; req.on('data', function(chunk){ body += chunk; }); req.on('end', function(){ fs.readFile(__dirname + '/data/notes.json', function(err, data){ if (err) throw err; console.log(body); var fileObj = JSON.parse(data.toString()); var postObj = JSON.parse(body); fileObj.notes.push(postObj); var returnjson = JSON.stringify(fileObj); fs.writeFile(__dirname + '/data/notes.json', returnjson, function(err){ if (err) throw err; res.send(returnjson); }); }); }); }); 

可能在notes.json中的示例:

 {"note": "Dear Diary: The authorities have removed the black pants from the couch"} 

这个工作,但我无法绕过我的头附加任何json在post(让我们假设在这种情况下没有嵌套的数据)。

编辑:不只是追加到一个文件。 需要附加到文件中的对象。

你可以在for ... in循环中简单地遍历post对象,并将其属性添加到文件对象中。 请记住,在这种情况下,如果属性键是相同的,它们的值将被覆盖。 为了避免它,你可以在Object.prototype.hasOwnProperty()的帮助下进行validation。

 app.post('/notes', function(req, res){ var body = ""; req.on('data', function(chunk){ body += chunk; }); req.on('end', function(){ fs.readFile(__dirname + '/data/notes.json', function(err, data){ if (err) throw err; console.log(body); var fileObj = JSON.parse(data.toString()); var postObj = JSON.parse(body); for(var key in postObj) { fileObj[key] = postObj[key]; } var returnjson = JSON.stringify(fileObj); fs.writeFile(__dirname + '/data/notes.json', returnjson, function(err){ if (err) throw err; res.send(returnjson); }); }); }); }); 

这是for ... each陈述,如果你不想覆盖属性。 新的属性会产生如下所示的后缀: _1_2等。您还可以使用类似shortid的内容来确保属性不会重复,但会更难看,也更不可读。

 for(var key in postObj) { if(fileObj.hasOwnProperty(key)) { while(true) { i++; newKey = key + '_' + i; if(fileObj.hasOwnProperty(newKey) == false) { fileObj[newKey] = postObj[key]; break; } } } else { fileObj[key] = postObj[key]; } }