1

So I have an existing JSON file where the login data is stored. How can I add new users to this JSON file with JavaScript or JQuery?

This is my JSON-File:

{
 "users": [
   {
    "username": "Tim",
    "password": "test1"
   },
   {
    "username": "Tom",
    "password": "test2"
   }
 ]
}
4
  • 2
    users.push({ "username": "jon", "password": "test2" }) Commented Dec 12, 2019 at 22:59
  • you want to write data to your jsonfile ? Commented Dec 12, 2019 at 23:00
  • Also usually password is hashed and not stored in raw form. If you are using Nodejs. You can push new data to this array and use fs package to update your JSON file Commented Dec 13, 2019 at 0:04
  • For Jquery, You can check this answer out - stackoverflow.com/a/17976034/6128530 Commented Dec 13, 2019 at 5:49

1 Answer 1

1

At the first put your data from login in data

var data  = {
 "users": [
   {
    "username": "Tim",
    "password": "test1"
   },
   {
    "username": "Tom",
    "password": "test2"
   }
 ]
}

And after that you shoud parse your json and put in jsonData and push your new user in it.

 var jsonData = JSON.parse(data);  //parse the JSON
 jsonData.users .push({        //add new user
 username :"Mohammad",
 password  :"test3",
 });

At the end stringfy your json data to a string

data= JSON.stringify(jsonData);
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.