0

I have a JSON file which contains:

[{"id":1,"first_name":"Judith","email":"[email protected]"},
{"id":2,"first_name":"Sarah","email":"[email protected]"},
{"id":3,"first_name":"Dorothy","email":"[email protected]"},
{"id":4,"first_name":"Christine","email":"[email protected]"},
{"id":5,"first_name":"Theresa","email":"[email protected]"},
{"id":6,"first_name":"Rebecca","email":"[email protected]"},
{"id":7,"first_name":"Chris","email":"[email protected]"},
{"id":8,"first_name":"Howard","email":"[email protected]"},
{"id":9,"first_name":"Sara","email":"[email protected]"},
{"id":10,"first_name":"Lois","email":"[email protected]"},
{"id":11,"first_name":"Jeffrey","email":"[email protected]"},
{"id":12,"first_name":"Teresa","email":"[email protected]"},
{"id":13,"first_name":"Susan","email":"[email protected]"},
{"id":14,"first_name":"Richard","email":"[email protected]"},
{"id":15,"first_name":"Ronald","email":"[email protected]"}]

I want to add one more element to it but I can't figure it out how. I have the following node code:

var jsonfile = require('jsonfile');
var util = require('util');

var file = 'data.json';
var jsonObj = {};
jsonfile.readFile(file, function(err, obj) {
    jsonObj = obj;

    new_obj = {"id":16,"first_name":"Florin","email":"[email protected]"};
    //jsonObj.push(new_obj)
    console.log(typeof jsonObj);

    /*jsonfile.writeFile(file, jsonObj, function (err) {
      console.error(err)
    })*/
});

I've tried to use push method, but obviously is not working because it is an object not an array, even if it looks as an array. Which would be a good way to add another row at the end of the object (or array - I'm confused)?

1

2 Answers 2

3

I believe you're forgetting to parse JSON. After reading the file, your code should be:

jsonObj = JSON.parse(obj);

instead of straight assignment.

Sign up to request clarification or add additional context in comments.

1 Comment

undefined:1 [object Object],[object Object],[object Object],[object Object],[object Object ^ SyntaxError: Unexpected token o at Object.parse (native) at /home/florin17/Desktop/Work/Express/server/app.js:10:20 at /home/florin17/Desktop/Work/Express/server/node_modules/jsonfile/index.js:20:5 at fs.js:268:14 at Object.oncomplete (fs.js:107:15)
1

Declare the variable

 var new_obj = {"id":16,"first_name":"Florin","email":"[email protected]"};

And then use push() as you have done already. Give it a try. It will work only if obj is json object as you mentioned in question.

Comments

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.