JSON file opens in new tab (I want to download)

Viewed 572

I have an anchor tag

<a target="_blank" href="./assets/.../sample.json" download="">Download Sample JSON</a>

If I use download attribute: it shows - Failed / Network Error

If I do not use download attribute: it opens the .json in new tab

Expected result : .json should be downloaded


I also have another anchor tag for CSV

<a target="_blank" href="./assets/.../sample.csv" download="">Download Sample CSV</a>

which perfectly downloads .csv every time.

1 Answers

You actually can't download a JSON file like that. You need some javascript. So add in

<a target="_blank" href="./assets/.../sample.json" download="" onClick="downloadJSON">Download Sample JSON</a>

and then in your js file or tags in your html add in:

  function downloadJSON(){

 var json = JSON.stringify(yourJSON);
 
        
        json = [json];
        var blobForYou = new Blob(json, { type: "application/JSON" });
         FileSaver.SaveAs(blobForYou);
}
Related