Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Object into JSON and downloading as a .json file in React

I have a javascript object that contains some information. I want to convert this into JSON and download it as a .json file. Seems like I can just to JSON.stringify(obj) to convert it into JSON but how do I actually download it as a .json file?

like image 797
Dawn17 Avatar asked Jul 06 '18 18:07

Dawn17


2 Answers

For those arriving here and searching for an easier solution:

         <a
            href={`data:text/json;charset=utf-8,${encodeURIComponent(
              JSON.stringify(YOURJSON)
            )}`}
            download="filename.json"
          >
            {`Download Json`}
          </a>
like image 141
Loïc V Avatar answered Sep 24 '22 16:09

Loïc V


I'm not sure this is a React-specific issue if you're just looking to download data via JavaScript, but here's a snippet I use that creates a link to download the data content, virtually clicking the element, and finally removing it from the DOM. It should support both modern browsers and older IEs:

private exportToJson(objectData: SomeObject) {
    let filename = "export.json";
    let contentType = "application/json;charset=utf-8;";
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      var blob = new Blob([decodeURIComponent(encodeURI(JSON.stringify(objectData)))], { type: contentType });
      navigator.msSaveOrOpenBlob(blob, filename);
    } else {
      var a = document.createElement('a');
      a.download = filename;
      a.href = 'data:' + contentType + ',' + encodeURIComponent(JSON.stringify(objectData));
      a.target = '_blank';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
  }

It's also worth noting that there are a number of ways to approach this as cited in this SO question.

like image 37
Jonathan Michalik Avatar answered Sep 25 '22 16:09

Jonathan Michalik