React:write to json file or export/download [no server]
I had a blob containing data and I had found a solution on stackoverflow and manipulated a bit, and succeded to download as a xlsx file. I am adding my code below, it might help you, too.
const blob = await res.blob(); // blob just as yours
const href = await URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.download = "file.xlsx";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
EDIT: I have written a function for your case, you can use below function, but be careful about "fileName" (not in "this.state" object in my case) and "myData" object that is stored in "this.state" object.
const downloadFile = async () => {
const {myData} = this.state; // I am assuming that "this.state.myData"
// is an object and I wrote it to file as
// json
const fileName = "file";
const json = JSON.stringify(myData);
const blob = new Blob([json],{type:'application/json'});
const href = await URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.download = fileName + ".json";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
For the ones like me here that are looking for an easier solution when you already have your JSON as a variable:
<button
href={`data:text/json;charset=utf-8,${encodeURIComponent(
JSON.stringify(YOURJSON)
)}`}
download="filename.json"
>
{`Download Json`}
</button>