Download file JSON JavaScript

Download file JSON JavaScript

Share on FaceBookShare on TwitterShare on WhatsApp
In this article I will explain with an example, how to download JSON object (Array) as File from Browser using JavaScript.
Initially a JSON object (Array) will be created and then it will be converted into a JSON String, then to BLOB object and ultimately downloaded (exported) as Text file from Browser using JavaScript.
HTML Markup
The following HTML Markup consists of an HTML Button. The HTML Button has been assigned an OnClick event handler which calls the DownloadJSON JavaScript function.
<input type="button" value="Download JSON" onclick="DownloadJSON()" />
JavaScript function to
download JSON object (Array) as File
Inside the DownloadJSON JavaScript function, first a JSON Array is created and then converted into a JSON string.
The JSON string is converted into a BLOB object which is later downloaded (exported) from Browser as JSON Text file using JavaScript.
<script type="text/javascript">
function DownloadJSON() {
//Build a JSON array containing Customer records.
var customers = new Array();
customers.push(["Customer Id", "Name", "Country"]);
customers.push([1, "John Hammond", "United States"]);
customers.push([2, "Mudassar Khan", "India"]);
customers.push([3, "Suzanne Mathews", "France"]);
customers.push([4, "Robert Schidner", "Russia"]);
//Convert JSON Array to string.
var json = JSON.stringify(customers);
//Convert JSON string to BLOB.
json = [json];
var blob1 = new Blob(json, { type: "text/plain;charset=utf-8" });
//Check the Browser.
var isIE = false || !!document.documentMode;
if (isIE) {
window.navigator.msSaveBlob(blob1, "Customers.txt");
} else {
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob1);
var a = document.createElement("a");
a.download = "Customers.txt";
a.href = link;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
</script>
Screenshot
JSON File downloading
Download JSON object (Array) as File from Browser using JavaScript
The downloaded JSON File
Download JSON object (Array) as File from Browser using JavaScript
Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer FireFox Chrome

* All browser logos displayed above are property of their respective owners.

Demo
View Demo
Downloads
Export_JSON_File_JavaScript.zip
Download Free Word/PDF/Excel API

Video liên quan

Related posts:

Post a Comment

Previous Post Next Post

Discuss

×Close