Like title says. I dont know how to update json data in vanilla javascript.. If you know how to do it please tell me if its even possible. If its not please help me with this. I can provide you info if you want to help me 🙂
I have tried to do alot of things but nothing worked. I know how to fetch info from json but i dont know how to store/update the data to the json.
This is what i tried but did not work:
saveToJson() {
let jsonFilePath = "../data/players.json";
fetch(jsonFilePath)
.then(response => response.json())
.then(data => {
for (let i = 0; i < data.players.length; i++) {
if (data.players[i].name === this.name) {
data.players[i].all_time_stats.kills = this.kills;
data.players[i].all_time_stats.headshots = this.headshots;
data.players[i].all_time_stats.deaths = this.deaths;
break;
}
}
fetch(jsonFilePath, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
});
}
2
Answers
You are using frontend JavaScript, meaning that all your code is run on the client (the user). The client can’t modify the server’s files.
To do this, you can setup a server and send the JSON from the client to the server, using
fetch()
. In the code below, I have created anexpress
server that serves your static files, and an endpoint that can modify the file.You can fetch the JSON in the same way, but on your client, use this code to modify the file:
Just remember that the client cannot modify the server on it’s own, and this will not be possible on a static site.
JSON is an acronym for JavaScript Object Notation, which makes it particularly easy to manipulate in JavaScript, as it is (almost) executable JavaScript as it comes.
So, the answer to your question "Is it possible to update json data in vanilla javascript?" is definitely, yes.
Just call
var obj = JSON.parse(jsonString)
.Then you can directly manipulate the JavaScript object:
obj.someValue = newValue
You can convert it back to a string if you need to send/save it somewhere using
JSON.stringify(obj)
When it comes to your code though, it looks like you’re trying to update a json file located on a server. Do you operate the server, and have access to the server code, or are you accessing a public API?
Your code does request that the server update the
players.json
to the values you specified, but if this is a public API it is very likely that the request is unauthorised and it will be impossible to update the data directly, as you are requesting. This is by design to prevent cheating in the game. Usually as a client, you are untrusted and cannot write any data to a leaderboard/stats API.