Reputation: 95
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
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");
good luck and try ...!!!
Upvotes: 3