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
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
- 5 JavaScript can not save a file. What you can do is send the data to the server and have a service/script that saves it for you. – Halcyon Commented Jan 14, 2016 at 15:05
- What's the real question here? Saving a file or editing the json file? If you want to find a way to edit the json file (properties), you can load the json, transform it into a javascript object and iterate through all properties to display some sort of input for every property. – Daniel Bauer Commented Jan 14, 2016 at 15:08
- the fact is that i want to edit it and save it :/ – saroten Commented Jan 14, 2016 at 15:13
-
@Halcyon Isn't it what
HTTP
PUT
method is designed for? – Lewis Commented Jan 14, 2016 at 15:13 -
@Tresdin you may be right about that but I don't think modern webservers implement
PUT
that way. It's really bad for security to accept any file. – Halcyon Commented Jan 14, 2016 at 15:17
1 Answer
Reset to default 3hi 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 ...!!!