If you're working with Javascript in the browser, it's important to note that writing files directly to the local machine is not allowed. However, a workaround is to download a JSON file to your computer using the Blob method.
You can achieve this by implementing the following code snippet:
const data = {
key: "value"
};
const fileName = "data.json";
const saveFile = (() => {
const a = document.createElement("a");
document.body.appendChild(a);
return (data, filename) => {
const json = JSON.stringify(data);
const blob = new Blob([json], { type: "application/json" });
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}
})
saveFile(data, fileName);