Rojakcoder

Tech and Biz Ramblings

Download JSON as a Text File

As a Web developer, I sometimes find a need to download some huge JSON object into a text file.

Modern browsers now come with some form of developer tool/console to help debug the monstrous amount of JavaScript in the Web page. For Chrome and Firefox, I simply press F12 to bring up the console. From the console, you can naturally copy the JSON object in its string form by first converting the object into a string like so:

JSON.stringify(obj);

Then highlight the output from the developer console and press Ctrl-C to copy. The trouble comes in when the object is huge - to the tune of thousands of properties.

When an object gets to that size, you will need to scroll to be able to select the complete output. Scrolling the console is itself a tiresome task with text that small. Moreover you run the risk of “over scrolling” such that you select two objects rather than one because you can’t tell the difference when they are simply chunks of text.

The best solution is to download the JSON as a text file and then use/manipulate the JSON from the file.

The way to do this is to create a function like this:

function download(filename, text) { var el = document.createElement(‘a’); el.setAttribute(‘href’, ‘data:text/plain;charset=utf-8,’ + encodeURIComponent(text)); el.setAttribute(‘download’, filename); el.click(); }

What this function does is it inserts a new <a> tag into the page. The purpose of this tag contains the href attribute as any hyperlink does, and a download attribute which downloads the contents (at least on modern browsers - I have not bothered to check compatibility on this one).

What’s interesting is the href attribute that uses a data URI. Modern browsers recognise the data URI scheme and together with the download attribute allows the user to download that content as a file.

To use it, simple call it like so:

download("file.json", JSON.stringify(jsonObj));

This function can actually be improved a bit. Herein lies another tip. Instead of passing text as a parameter, move the parser inside the function, and at the same time, “pretty print” the JSON! (Use this if you just want to save JSON data)

function download(filename, json) {
    var el = document.createElement('a'),
        text = JSON.stringify(json, null, 4);
    el.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    el.setAttribute('download', filename);
    el.click();
}

Usage is now:

download("file.json", jsonObj);

Pretty handy! This actually is a function that is perfectly suited to be made into a browser extension. I would do it now myself if not for other pressing issues that are on my plate. I look forward to anyone creating something like this!

comments powered by Disqus

Related contents

json (1)
download (1)