Explain Codes LogoExplain Codes Logo

Download JSON object as a file from browser

javascript
prompt-engineering
functions
callbacks
Anton ShumikhinbyAnton Shumikhin·Oct 6, 2024
TLDR
const downloadJSON = (obj, name) => { const dataUri = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj)); const anchorElement = document.createElement('a'); anchorElement.href = dataUri; anchorElement.download = `${name}.json`; document.body.appendChild(anchorElement); // Bend Firefox to your rule anchorElement.click(); document.body.removeChild(anchorElement); // Cleanup! Leave no trace behind. } // Invoke like this: downloadJSON({ key: 'value' }, 'desiredFilename');

Voila! Start enjoying hassle-free exporting of a JSON object to a file in the browser using downloadJSON. Feed it with your JSON data and preferred filename and watch the magic unfold.

Diving deep: The step-by-step guide

Let's peel back the layers and dive deep into the how and why. We will go through this process step by step.

Encoding data

Properly structure your JSON object. Make use of the JSON.stringify method, as well as encodeURIComponent, to ensure a safe transformation of the data.

const dataUri = "data:text/json;charset=utf8," + encodeURIComponent(JSON.stringify(obj));

In other words, we're grooming your data for the party—the downloadable form!

Crafting an anchor

Here we are, creating a virtual anchor which would soon take the form of a downloadable file in your browser. We know, crazy huh?

const anchorElement = document.createElement('a'); anchorElement.href = dataUri; anchorElement.download = `${filename}.json`;

Just like assigning a GPS location to your Uber driver. The href attribute is your location(dataUri), and the download attribute is your destination(filename).

Tricking the browser

Next up, we're being a little sneaky and tricking Firefox into triggering an automatic download by adding our anchor to the body.

document.body.appendChild(anchorElement);

Who knew browsers could be so easily fooled? (Shh, don't tell Firefox.)

Click and clean

At last, we automate a click on our virtual anchor (initiating the download), then swiftly remove it.

anchorElement.click(); document.body.removeChild(anchorElement);

It's like we're pulling a magical rabbit out of the hat, and then niftily pushing it back in, leaving no trace behind!

For the adventurous: Alternative approaches

Blob and URL.createObjectURL

No, this section isn't about scary monsters. Your large JSON objects might need a different approach using Blob and URL.createObjectURL.

const objectBlob = new Blob([JSON.stringify(obj)], {type : 'application/json'}); const url = URL.createObjectURL(objectBlob); const anchorElement = document.createElement('a'); anchorElement.href = url; anchorElement.download = `${name}.json`;

Blobbing to the rescue! More efficient and puts down mutated encodeURIComponent.

FileSaver.js to the rescue

More adventurous? Use Filesaver.js. It makes the file saving operation as smooth as butter.

saveAs(new Blob([text], {type: "application/json;charset=utf-8"}), 'filename.json');

File saving can't get any simpler... Until it does.

JSON Formatting

Let's not leave our JSON all squished and hard to read. Let's pretty-print it for human-friendliness.

JSON.stringify(obj, null, 2);