Dawn17
Dawn17

Reputation: 8297

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?

Upvotes: 11

Views: 17161

Answers (3)

Loïc V
Loïc V

Reputation: 635

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>

Upvotes: 11

NullPointer
NullPointer

Reputation: 7368

You won't be able to create a file directly on your computer's file system as this would be a huge security risk. You cannot do this from a web page using JavaScript.

You could write a server side service to post your state to and it creates a file - you may then download the file or be content with where your server side stores it.

Another way via inMemory Create a file in memory for user to download, not through server

Upvotes: -1

Jonathan Michalik
Jonathan Michalik

Reputation: 1532

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.

Upvotes: 28

Related Questions