Saving a Javascript object to a file

Viewed 23849

I need to save a Javascript object to a file, so it can be easily reloaded into a variable, modified and eventually re-saved. Is this feasible in Javascript and if so what's the best way to approach it. For example if I have:

o = {"test": 2};

How can I save it to a file, load, modify and save it? Exactly like pickle in Python.

Thanks.

3 Answers

You can save a file using the "download" attribute on a element. This is how it is done programmaticaly:

function saveJSON() {
   let data = "Whatever it is you want to save";
   let bl = new Blob([data], {
      type: "text/html"
   });
   let a = document.createElement("a");
   a.href = URL.createObjectURL(bl);
   a.download = "data.json";
   a.hidden = true;
   document.body.appendChild(a);
   a.innerHTML =
      "someinnerhtml";
   a.click();
}
Related