9

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?

Dawn17
  • 7,825
  • 16
  • 57
  • 118

3 Answers3

26

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.

Jonathan Michalik
  • 1,492
  • 14
  • 15
  • This stores json data as "{\"name\":\"cliff\",\"age\":\"34\"}" f.e. Is there a way to prettify it so that the escape characters are removed and every value is on a new line? – Rik van Velzen Dec 16 '19 at 14:53
  • Interestingly, I'm not able to replicate the escape character issue, but for pretty-print, you can use the 3rd argument for `JSON.stringify` so something like `JSON.stringify(objectData, null, 2)` which will include `LF` characters for pretty-printing and 2 spaces per level of depth in the object being stringified. – Jonathan Michalik Dec 17 '19 at 00:07
  • I'll add separately that the 2nd argument of `JSON.stringify` is a replacer which can be a function that modifies keys and values in the object. I imagine you could use a function similar to the one provided in [this answer](https://stackoverflow.com/a/34649086) to remedy extraneous characters being printed – Jonathan Michalik Dec 17 '19 at 00:09
9

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>
e-fisher
  • 659
  • 1
  • 6
  • 8
Loïc V
  • 517
  • 7
  • 9
  • 2
    Using JSON.stringify(YOURJSON, null, '\t') instead will also download the json formatted. I've proposed the change. – Bouramas Feb 18 '21 at 10:59
-1

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

NullPointer
  • 7,094
  • 5
  • 27
  • 41