skip to Main Content

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


  1. 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 an express server that serves your static files, and an endpoint that can modify the file.

    const express = require("express"); // npm i express
    const fs = require("fs"); // the filesystem module can modify files
    const path = require("path"); // fs needs absolute paths
    
    
    const server = express(); // create an express app
    
    server.use(express.static("public")); // this will serve all the files in ./public
    
    server.post("/modify", async (req, res) => {
        // Get the JSON data from the request body
        const json = req.body;
    
        // Save the JSON data to a file
        fs.writeFile(
            path.join(__dirname, "public", "myFile.json"),
            JSON.stringify(json), "utf-8", (err) => {
                if (err) {
                    console.error("Error writing file:", err);
                    res.status(500).send("Internal Server Error");
                } else {
                    console.log("File saved successfully");
                    res.send("File saved successfully");
                }
        });
    });
    
    server.listen(80); // start the webserver on port 80
    

    You can fetch the JSON in the same way, but on your client, use this code to modify the file:

    fetch("/modify", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: jsonData
    });
    

    Just remember that the client cannot modify the server on it’s own, and this will not be possible on a static site.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search