3

I am trying to make an anchor element to directly download a JSON file, but it redirects to a new tab and the download does not start.

The code I am writing in HTML is given below

<a href="https://raw.githubusercontent.com/HarshNarwariya/DSA/master/Blind%2075%20Must%20Do%20Leetcode/Leetcode%2075%20Problems.json" download>Download Data</a>

Download Data

Above is an example of my running code.

I need an anchor element, on which I click and the download starts, not the new tab with the view of the data.

Harsh Narwariya
  • 498
  • 2
  • 11

1 Answers1

1

You linked page is an html page with a json string between a pre tag. In this case i would use javascript.

working example

function downloadObjectAsJson() {
  const exportName = "youjson.json";
  fetch('https://raw.githubusercontent.com/HarshNarwariya/DSA/master/Blind%2075%20Must%20Do%20Leetcode/Leetcode%2075%20Problems.json').then(function
  (response) {

    return response.json();
  }).then(function (data) {

    var dataStr = "data:text/json;charset=utf-8," +
    encodeURIComponent(JSON.stringify(data));
    var downloadAnchorNode = document.createElement('a');
    downloadAnchorNode.setAttribute("href",     dataStr);
    downloadAnchorNode.setAttribute("download", exportName + ".json");
    document.body.appendChild(downloadAnchorNode); // required for firefox
    downloadAnchorNode.click();
    downloadAnchorNode.remove();

  }).catch(function (err) {

    console.warn('Something went wrong.', err);
  });


}

function dlJson() {
  downloadObjectAsJson();
}
<a href="#" onclick="dlJson()">Download your JSON file</a>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79