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"
   }
 ]
}
jon3laze
  • 3,188
  • 6
  • 36
  • 69
Jufg
  • 13
  • 2

1 Answers1

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);
Mohammad
  • 127
  • 1
  • 12