saroten
saroten

Reputation: 95

Change a value in a json file using javascript

I would like to change values of a json file by using javascript. Here is the json file :

{ 
  "login": "",
  "password": "",
  "ip": "",
  "port": "", 
  "protocol": ""
} 

And here is what I've tried to change the values :

$('#save').click(function () {
    var login = $("#login").val();
    var password = $("#password").val();
    var ip = $("#ip").val();
    var port = $("#port").val();
    var protocol = $("#protocol").val();
    var jurl = "setting.json";

    $.getJSON(jurl,
    {
        format: "json"
    },
    function (data) {
        data.login = login;
        data.password = password;
        data.ip = ip;
        data.port = port;
        data.protocol = protocol;
    }); 
 });

I use <input type="text"> to define the values

Upvotes: 2

Views: 14208

Answers (1)

BlackHack123
BlackHack123

Reputation: 349

hi for change values this is a little example

    var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
                  {'Id':'2','Username':'Steve','FatherName':'Johnson'},
                   {'Id':'3','Username':'Albert','FatherName':'Einstein'}]

for (var i=0; i<jsonObj.length; i++) 
{
      if (jsonObj[i].Id == 3) {
        jsonObj[i].Username = "Thomas";
        break;
      }
}

Here's the same thing wrapped in a function:

function setUsername(id, newUsername) {
  for (var i=0; i<jsonObj.length; i++) {
    if (jsonObj[i].Id === id) {
      jsonObj[i].Username = newUsername;
      return;
    }
  }
}

// Call as
setUsername(3, "Thomas");

check here the example

good luck and try ...!!!

Upvotes: 3

Related Questions