Welcome folks today in this blog post we will be exporting array of json objects
to csv and download it as attachment in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> <script src="script.js"></script> </html> |
And now we need to make the script.js
file that we have included inside the html
so copy paste the below code
script.js
First of all we will be declaring an array of json objects
inside the code as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
itemsNotFormatted = [ { model: 'Samsung S7', chargers: '55', cases: '56', earphones: '57', scratched: '2' }, { model: 'Pixel XL', chargers: '77', cases: '78', earphones: '79', scratched: '4' }, { model: 'iPhone 7', chargers: '88', cases: '89', earphones: '90', scratched: '6' } ]; |
So as you can see it is an array of json objects. Each object has a series of properties that we need to convert csv
file (comma separated values) so for that we need to write the javascript code
Now we will be removing the commas
from the array of objects to avoid confusion so make a new object
as shown below and after that we will be using the foreach
loop to iterate through all the records of array of records
1 2 3 4 5 6 7 8 9 10 11 |
var itemsFormatted = []; // format the data itemsNotFormatted.forEach((item) => { itemsFormatted.push({ model: item.model.replace(/,/g, ''), // remove commas to avoid errors, chargers: item.chargers, cases: item.cases, earphones: item.earphones }); }); |
Now we have the object
that we will pass to the function which will convert the array of json objects to csv file. Now we also need to provide some information about the name of the file that you want to give and also the base object from which the csv file will be constructed for that also we need to add the same properties that are there inside the array of json objects as shown below
1 2 3 4 5 6 7 8 |
var headers = { model: 'Phone Model'.replace(/,/g, ''), // remove commas to avoid errors chargers: "Chargers", cases: "Cases", earphones: "Earphones" }; var fileTitle = 'orders'; // or 'my-unique-title' |
As you can see we have initialized the header
object that we will pass to the function where we will convert json to csv. And after that we are providing the name of the file that we have to give to the output file.
After that we will call the function now where we will convert the array of json objects to csv file as shown below
1 |
exportCSVFile(headers, itemsFormatted, fileTitle); // call the exportCSVFile() function to process the JSON and trigger the download |
Now we will define this function that we are calling above. Just copy paste the below code
1 2 3 4 5 6 7 8 9 10 11 |
function exportCSVFile(headers, items, fileTitle) { if (headers) { items.unshift(headers); } // Convert Object to JSON var jsonObject = JSON.stringify(items); var csv = this.convertToCSV(jsonObject); } |
As you can see in the above code we are first of all adding the
headers inside the csv file
by using the unshift()
method which will actually the header object into the beginning of the array and then we are converting the json
object to string using the JSON.stringify()
method and after that we are providing the output
filename that we have received as an argument. If no name was provided then we are providing the default file name.
And now we are calling the utility
function which will actually convert the json
to csv format which is the comma separated values. Now we need to define this function at the very top
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function convertToCSV(objArray) { var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; var str = ''; for (var i = 0; i < array.length; i++) { var line = ''; for (var index in array[i]) { if (line != '') line += ',' line += array[i][index]; } str += line + '\r\n'; } return str; } |
As you can see we are passing the json
object to this method that we need to convert to csv format. Inside this method we are first of all checking whether the passed json object is an array
or object. Depending on that we are calling the JSON.parse()
method to convert the json to an array. And then we running the for loop to insert the comma
in between the values of the array. And after adding all the commas in between the array values we are simply returning the output string from this function.
As you can see it has converted our array of objects to the comma separated values csv string as you can show above.
Now we need to download this csv
string in a file and download it as an attachment. For that we are using the anchor
tag and setting the dynamic href
and here we are passing the csv
data string which is base64. First of all we have converted the csv
string to the blob object. And from that blob object we have constructed this data url for this file. Now after that we are setting the attribute of the download to download the file as an attachment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var exportedFilenmae = fileTitle + '.csv' || 'export.csv'; var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); if (navigator.msSaveBlob) { // IE 10+ navigator.msSaveBlob(blob, exportedFilenmae); } else { var link = document.createElement("a"); if (link.download !== undefined) { // feature detection // Browsers that support HTML5 download attribute var url = URL.createObjectURL(blob); link.setAttribute("href", url); link.setAttribute("download", exportedFilenmae); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } |
As you can see when you load the page inside the browser you will see the csv
file will be automatically downloaded as an attachment.
Full Javascript Code
script.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
function convertToCSV(objArray) { var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; var str = ''; for (var i = 0; i < array.length; i++) { var line = ''; for (var index in array[i]) { if (line != '') line += ',' line += array[i][index]; } str += line + '\r\n'; } return str; } function exportCSVFile(headers, items, fileTitle) { if (headers) { items.unshift(headers); } // Convert Object to JSON var jsonObject = JSON.stringify(items); var csv = this.convertToCSV(jsonObject); console.log(csv) var exportedFilenmae = fileTitle + '.csv' || 'export.csv'; var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); if (navigator.msSaveBlob) { // IE 10+ navigator.msSaveBlob(blob, exportedFilenmae); } else { var link = document.createElement("a"); if (link.download !== undefined) { // feature detection // Browsers that support HTML5 download attribute var url = URL.createObjectURL(blob); link.setAttribute("href", url); link.setAttribute("download", exportedFilenmae); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } } var headers = { model: 'Phone Model'.replace(/,/g, ''), // remove commas to avoid errors chargers: "Chargers", cases: "Cases", earphones: "Earphones" }; itemsNotFormatted = [ { model: 'Samsung S7', chargers: '55', cases: '56', earphones: '57', scratched: '2' }, { model: 'Pixel XL', chargers: '77', cases: '78', earphones: '79', scratched: '4' }, { model: 'iPhone 7', chargers: '88', cases: '89', earphones: '90', scratched: '6' } ]; var itemsFormatted = []; // format the data itemsNotFormatted.forEach((item) => { itemsFormatted.push({ model: item.model.replace(/,/g, ''), // remove commas to avoid errors, chargers: item.chargers, cases: item.cases, earphones: item.earphones }); }); var fileTitle = 'orders'; // or 'my-unique-title' exportCSVFile(headers, itemsFormatted, fileTitle); // call the exportCSVFile() function to process the JSON and trigger the download |