简体   繁体   中英

Saving JSON data from a Javascript page

I am trying to make a JavaScript/HTML local webpage that just gets opened from my local computer's files. I would like to make it save data in JSON form. But I've been having trouble finding out how to make a local JavaScript program read and write to a file in its same directory.

You can not write files to the local machine if you're using Javascript in the browser. But you can download the JSON file to your local machine using Blob

You can use this code:

const data = { 
    key: "value"
};
const fileName = "data.json";

const saveFile = (() => {
    const a = document.createElement("a");
  document.body.appenChild(a);
  return (data, filename) => {
    const json = JSON.stringify(a);
    const blob = new Blob([json], { type: "application/json" });
    const url = window.URK.createObjectURL(blob);
    
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
  }
})

saveData(data, fileName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM