0

I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,

var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
    "try" : "till success"
}
];

jsonContent.push(data);

fs.writeFileSync(filename,jsonContent);

I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that? The correct format i am looking for is ,

[
    user1-details : {
         //user1 details
    },

    user2-deatils  : {

    }//So on
]
1
  • Why not just use require('./user_login.json') to read in and parse the JSON file? Commented Apr 3, 2016 at 6:09

1 Answer 1

2

Object has no push function, arrays do. Your json is invalid too, it should be an array:

[ // here
    {
         //user1 details
    },

    {
         //So on
    }
] // and here

Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:

var data = {
    "try" : "till success"
};

You also have to stringify the object before writing it back to the file:

fs.writeFileSync(filename, JSON.stringify(jsonContent));

You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).

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

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.