Download JSON object as a file from browser
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.
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?
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
.
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.
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
.
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.
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.
Was this article helpful?