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
6
  • JSON.push(newJSONObject) Commented Jun 24, 2015 at 12:59
  • If taskArrObj is an array then use taskArrObj.push(newJSONObject) Commented Jun 24, 2015 at 13:01
  • whats the format of tasks.json? Commented Jun 24, 2015 at 13:01
  • TypeError: Cannot read property 'push' of undefined Commented Jun 24, 2015 at 13:02
  • whats the format of tasks.json? >> that's simply file: [{xx:true, yy:"bbb", zz:"10."} , {xx:true, yy:"bbb", zz:"10."}] Commented Jun 24, 2015 at 13:02

2 Answers 2

1

use this:

var updatedJSON=taskArrObj.push(newJsonObj);
Sign up to request clarification or add additional context in comments.

9 Comments

It means your taskArrObj is empty, possibly task.json could not loaded into it
Do you mean task.json file cannot be blank? So how data gonna consists empty task.json file?
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
So can I create empty JSON variable if my JSON file is empty?
Thats just error checking. You can do that. If you specify encoding then file contents will be available in your variable
|
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);

1 Comment

How to convert my {xx:true, yy:"bbb", zz:"10."} to newJsonObj? for normally pushing into array ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.