0
var taskArrObj = JSON.parse(fs.readFileSync("tasks.json"));
var newJsonObj = {xx:true, yy:"bbb", zz:"10."};

var updatedJsonObj = taskArrObj + newJsonObj ??? append JSON array with new JSON element?

res.json(updatedJsonObj);//send splitted JSON array in response

2 Answers2

1

use this:

var updatedJSON=taskArrObj.push(newJsonObj);
Hammad
  • 1,893
  • 2
  • 16
  • 37
  • It means your taskArrObj is empty, possibly task.json could not loaded into it – Hammad Jun 24 '15 at 13:05
  • Do you mean task.json file cannot be blank? So how data gonna consists empty task.json file? – Spacemaster Jun 24 '15 at 13:07
  • Yes you are trying to call push method on a object that does not exist. This is the error. Graham has given a explanation why task.json may not be loading – Hammad Jun 24 '15 at 13:08
  • So can I create empty JSON variable if my JSON file is empty? – Spacemaster Jun 24 '15 at 13:13
  • Thats just error checking. You can do that. If you specify encoding then file contents will be available in your variable – Hammad Jun 24 '15 at 13:19
  • function readJsonContent() { fs.readFile('tasks.json', function read(err, data) { if (err) { throw err; } taskArrObj = JSON.parse(fs.readFileSync("tasks.json", "utf8")); }); } – Spacemaster Jun 24 '15 at 13:22
  • how can I check if my file is empty? – Spacemaster Jun 24 '15 at 13:23
  • Already good answer for that availabe: [Check if JSON is empty](http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object) – Hammad Jun 24 '15 at 13:24
  • I added checking for Exceptions: try{ taskArrObj = JSON.parse(fs.readFile("tasks.json")); return true; }catch (err) { return false; } – Spacemaster Jun 24 '15 at 13:59
0

As per the docs:

If encoding is specified then this function returns a string. Otherwise it returns a buffer.

readFileSync returns a buffer if you don't specify an encoding. JSON.parse will only accept a String as a parameter. Pass an encoding in:

var taskArrObj = JSON.parse(fs.readFileSync("tasks.json", "utf8"));
taskArrObj.push(newJsonObj);
CodingIntrigue
  • 65,670
  • 26
  • 159
  • 166