[javascript] Download JSON object as a file from browser

ES6+ version for 2021; no 1MB limit either:

This is adapted from @maia's version, updated for modern Javascript with the deprecated initMouseEvent replaced by new MouseEvent() and the code generally improved:

const saveTemplateAsFile = (filename, jsonToWrite) => {
    const blob = new Blob([jsonToWrite], { type: "text/json" });
    const link = document.createElement("a");

    link.download = filename;
    link.href = window.URL.createObjectURL(blob);
    link.dataset.downloadurl = ["text/json", link.download, link.href].join(":");

    const evt = new MouseEvent("click", {
        view: window,
        bubbles: true,
        cancelable: true,
    });

    link.dispatchEvent(evt);
};

If you want to pass an object in:

const myObj = {};
const myObjAsJson = JSON.stringify(myObj);

saveTemplateAsFile(myObjAsJson);