In this tutorial I will show you how to convert JSON data to CSV and download CSV file.

Although this is very common and is available  elsewhere, but most of the programs fail to download the data when using IE below 10.Below what I’m going to show you a solution that will work on all browsers including IE8+.

View demohere
Download Codehere

index.html

Internet explorer download


Enter JSON data

Click below button to download CSV file for internet explorer and other browsers


 

We will be downloading the data in the text area.

Please Note that for this to work in IE it necessary to include <!DOCTYPE html> at the beginning of the html document this makes sure that your document is rendered in standard mode,else it will throw a JSON undefined error.

internetdownload.js


$(document).ready(function(){
$('.download').click(function(){
var data = $('#txt').val();
if(data == '')
return;
JSONToCSVConvertor(data, "testData", true);
});
});

So basically on click of the download button this will fetch JSON data from textarea and pass to JSONToCSVConvertor function.

and pass 3 parameter to JSONToCSVConvertor function that is,

  • JSONData – for JSON data
  • ReportTitle – for title of download file
  • ShowLabel – for generate the Label/Header

Before learning more about the JSONToCSVConverter function,lets look at the below function.

internetdownload.js


function msieversion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return true
{
return true;
} else { // If another browser,
return false;
}
return false;
}

Now this function is used to tell if the browser used is IE or not.We will use this function to decide which method should be used to download the required JSON data as a CSV file.

This function returns a boolean value as true if the browser used is Internet Explorer else false is returned.

Now lets have a look at the JSONToCSVConvertor function,

internetdownload.js


function JSONToCSVConvertor(JSONData,fileName,ShowLabel) {
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
if (ShowLabel) {
var row = "";
for (var index in arrData[0]) {
row += index + ',';
}
row = row.slice(0, -1);
CSV += row + '\r\n';
}
for (var i = 0; i < arrData.length; i++) {
var row = "";
for (var index in arrData[i]) {
var arrValue = arrData[i][index] == null ? "" : '="' + arrData[i][index] + '"';
row += arrValue + ',';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
if (CSV == '') {
growl.error("Invalid data");
return;
}
var fileName = "Result";
if(msieversion()){
var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + CSV);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
IEwindow.close();
} else {
var uri = 'data:application/csv;charset=utf-8,' + escape(CSV);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}

So in this function firstly it will convert JSON object to proper CSV formatted data by separating values with comma , spaces and new lines.

and then msieversion function will check whether it is IE or now based on that it will return true or false.

If it’s IE then what we basically do?

  • var IEwindow = window.open() :-  Open new window.
  • IEwindow.document.write(‘sep=,\r\n’ + CSV)  :-  Write all CSV data with sep= in that window.
  • IEwindow.document.close() :- Close writing document.
  • IEwindow.document.execCommand(‘SaveAs’, true, fileName + “.csv”) :- Force download file with assigned “filename.csv”.
  • IEwindow.close() :-  Close window

if it’s not then?

  • var uri = ‘data:application/csv;charset=utf-8,’ + escape(CSV) :- Set proper format in which will convert data (i.e: “CSV” this does not works with IE as a result there is a problem downloading and we have to use the method described above)
  • var link = document.createElement(“a”) :- Create link element
  • link.href = uri :- Pass data to link href
  • link.style = “visibility:hidden” :-  styling for hiding link
  • link.download = fileName + “.csv” :-  Create link for download with assigned appropriate name
  • document.body.appendChild(link) :- append that link to body
  • link.click() :- Link click event

 

69 Comments

      1. i dont want to open a new window and write all data in that can you please help me in this.
        i want that without opening a new window my file should be downloaded.

      1. Thank you for quick response!

        Sorry, this is my environment’s problem, maybe.
        my pc is installed Office365.
        I have changed file extension ‘.csv’ to ‘.txt’

        or

        I have added Registry Value

        [HKEY_CLASSES_ROOT\.csv]
        “PerceivedType”=”document”

        then it’s working.

        I try it on not installed Office365, then it worked as it is.

    1. Hi,
      I have checked in Safari it’s downloading file properly. and also checked that file is downloaded or not in your download folder.
      Can you please describe more on your problem so that i can resolve.
      Thanks.

  1. Thank you for the info. I have same implementation for similar requirement. Two issues with this:
    1) If you open downloaded file in notepad, we will see a new line with content: sep=,
    2) Download in IE shows two windows. One with all the csv content which doesn’t happens in other browsers and another a save as dialog with file name without extension. Even file types doesn’t have csv. Though it saves as csv its very confusing for customer.

    1. Hi VJ,
      Yes you are right. When you open that file in notepad then that will show “sep=,”, But it will show correct when you open that file in Excel.
      And for IE it will show 2 window because eariler IE version doesnot allow you to download CSV file as required. so this is a just another method for download CSV file.
      And also i have checked in my system browsers and it’s download properly with CSV extension.
      Thanks.

  2. It works fine except the fact that it opens a new tab with data in IE which looks weird, how can this be avoid?

  3. its not working at all with me. can you please email me? i need to submit the work tonight! thanks alot

    1. Hi Shakthi,
      Just i have checked in Microsoft office and its showing proper data. But not in WPS Spreadsheet. So need to check settings separation of data for WPS Spreadsheet. Will get back to u once solved.
      Thanks.

  4. Nice example. thanks! The one issue that I’ve found is the function to format the csv doens’t handle data with a comma in it properly. For example… if you have a value of “Land, Cruiser” it ends up breaking the CSV format and blocking into two columns… you can see this in your example just by inserting a comma in any of the values.

  5. Hi @Inaam Hussain great tutorial. Great job. can u please help me how do i stop opening new tab in IE.Just want to show saveAs popup.

    1. Hi Sarang,
      We have used another approach, because older version IE doesn’t allow to download CSV file.
      Newer version of IE allows as save as popup. but for older version we need to use this approach.
      Thanks.

  6. Hi,Inaam Hussain,

    I am not able to download CSV in safari browser version 5.1.7. I am getting error ‘undefined’ is not a function (evaluating : ‘link.click()’)…Although it works for Chrome and firefox

  7. He Guy,
    it don’t work very well as i want with IE 9, it open a new browser and popup windows for downloading and saving the file csv.
    it is possible after click to download without open the windows save popup ?

  8. Hi Hussain,
    For IE some system is working fine and Some system is not working, anything setting for those system. please give me some solution, b’coz developer system is working and QA system is not working showing error ‘XML5619: Incorrect document syntax line 1

  9. Hi Inaam,

    Your JSON to CVS works great in Chrome. Havent tested it in Safari and Firefox, but in IE (8,9,10, and 11), when I click on button to download csv file, the browser refreshes and quickly prints the data and goes away. I dont see file get downloaded.

    Here is my JSFiddle. http://jsfiddle.net/veyzws4b/

    1. Hi Ray,
      I think it should show download popup when its print data to new window in IE. and from there you can download.
      We have used different approach for IE, because all IE browser doesn’t allow to download csv file.
      Thanks.

      1. Hi Inaam,

        Did u find a fix for Safari browser. I am still having issue with Safari browser where the file name downloads with no name (unknow). My requirement is to have a file name to it.

        Thanks,
        Amisha

  10. var myObj = {“media_portal”:{“usersList”:[{“userId”:”103″,”userName”:”[email protected]”,”firstName”:”joe”,”latName”:”sa”,”isActive”:”1″,”customerId”:null,”customerCode”:””,”customerName”:””,”agreementId”:”4,13″,”agreementName”:”hsbccc, timessample”,”agreementCode”:”hscc, timessampl”},{“userId”:”92″,”userName”:”[email protected]”,”firstName”:”ashisha”,”latName”:”sharma”,”isActive”:”1″,”customerId”:”33″,”customerCode”:”12332″,”customerName”:”jonny”,”agreementId”:””,”agreementName”:””,”agreementCode”:””}]}};

    this is my code in json ., i want remove first node media_portal and userlist and download only json objects into csv file .. pls help me

    1. Hi kirangowda,
      You manually need to change in code while selecting json data. for example if your json data is in ‘JSONData’ object. so while conversion you have to pass JSONData.media_portal.usersList. that will convert as what you need.
      Thanks

  11. HI,

    The code works properly for me but I am able to rename the file in IE11 and when i rename the file the file changes its extension to .txt automatically. Can we default the file name and extension and alsways prompt the user to save directly.

    My local machine it’s working fine but the same is not working in QA machine and I am using JSP and not HTML to use the

    Sandeep

    1. Hi sandeep,
      in existing code it’s already saving file in csv format. see belo code. instead csv you can change to any extension you want.
      IEwindow.document.execCommand(‘SaveAs’, true, fileName + “.csv”);
      Thanks.

  12. 1. I am using IE9 , Is there any way I can save as .xls or .xlsx not in .csv ? without changing the file name.?

    2. And one more issue if I am changing the file name in popup window , its saving as unknown file format. Is there any way I can change the file name on popup window and SaveAs different file name ?

    Thanks,
    Satish.

    1. Hi Satish,
      1. yes you can change file name extension in “IEwindow.document.execCommand(‘SaveAs’, true, fileName + “.csv”)” line of code.
      2. In current version it is saving as .csv file only. if you need to change filename in popup then you may need to change the code as per your requirement.
      Thanks.

      1. I changed the filename extension as “IEwindow.document.execCommand(‘SaveAs’, true, fileName + “.xlsx”)” , file saved but not able to open the file , I am getting error message “Excel cannot open the “filename.xlsx” because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.”

  13. Hi Inaam, its great example but in chrome its working fine. In IE it is opening new window tab and showing json data in new tab then, when clicking on save, the new tab closing and download completed. Is there any way to avoid to show the json data in new tab?

    1. Hi Arat,
      We have used another approach, because older version IE doesn’t allow to download CSV file.
      Newer version of IE allows as save as popup. but for older version we need to use this approach.
      Thanks.

  14. This almost works in the Edge browser as the new window opens and closes immediately, but without a save dialog. If I can work around it, I’ll post my results.

    1. Hi Scott,
      You can use following piece of code to resolved your problem,

      var blob = new Blob( [ “A,B\nC,D” ], { type: “text/csv” } );
      navigator.msSaveOrOpenBlob( blob, “strings.csv” );

  15. Hi,
    I am not able name the file for safari browser it is downloading as unknown file.
    Can you please help me out?

    Thanks
    San

    1. Hi San,
      Can you please try following code for safari,

      var blob = new Blob( [ “A,B\nC,D” ], { type: “text/csv” } );
      navigator.msSaveOrOpenBlob( blob, “strings.csv” );

      1. Hi Inaam,
        When i try this code getting below error:
        ” navigator.msSaveOrOpenBlob is not defined or not a function”
        Can you please suggest on this?

          1. The same problem is with me.
            first fillename is Unknown-xx with no extension
            second when i used navigator.msSaveOrOpenBlob it says that navigator.msSaveOrOpenBlob() is not a function.
            navigator is a variable but it does not contain definition for msSaveOrOpenBlob as a function or anything else.

  16. HI Inaam Hussain,

    It is very useful article you shared here.
    But I have another problem, My requirement is Columns should be auto sized based on larger column. Can we increase the SIze of Columns.?
    If so will you please assist me how to do that ?? Thanks in Advance

  17. hi
    Thank you very much but how can i set text format in csv, Iwant to store 34545677987745643678
    but the value is appended with 0000 at last.how can i do into text format in csv with this code.

  18. Hi Innam,

    Any Idea how to remove “id” column from export. Currently it’s adding one extra column “id” in .csv file.

    Thanks,
    Vijay

Leave a Reply

Your email address will not be published. Required fields are marked *