Home > other >  How to write to a JSON file in javascriptp?
How to write to a JSON file in javascriptp?

Time:05-19

I am trying to write to a JSON file in a client side react web app. I have a nested object and I would like to be able to save this as a JSON file that a user can download.

Is this possible?

For example, here is my javascript object is:

{
  summary: {
    totals: {
      apples: 3,
      oranges: 2,
    }
  }
}

CodePudding user response:

Yes Tyler, it is very possible.

You need to make use of blobs to do that.

Here's a sample that downloads a file containing the text "I'm a ninja!" :

let txt = "I'm a ninja"; // we all want to be one, don't we? ;)

let blob = new Blob([txt], {type: 'text/plain'});

// Only way to initiate a download is by clicking a download link,
// so let's make one
let ln = document.createElement('a');
ln.href = URL.createObjectURL(blob);
ln.download = 'ninja.txt';
ln.click(); // trigger the download

// Remove the blob url reference to free up memory
URL.revokeObjectURL(ln.href);

The only change you'd have to make is to replace txt's content with a string version of the json by calling JSON.stringify on the object. Oh, and you should also change the file name to something like data.json.

You can learn more about blobs here.

  • Related