Download JSON data in CSV format Cross Browser Support

December 7, 2014
by Inaam Hussain

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
<!DOCTYPE html>
<html>
  <head>
     <title>Internet explorer download</title>
     <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
     <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
     <script src="js/internetdownload.js" type="text/javascript"></script>
  </head>
  <body>
    <div align="center">
    <h3><u>Enter JSON data</u></h3>
    <div class="mydiv">    
            <textarea cols="100" rows="15" class="txtarea" id="txt">[{"Vehicle":"BMW","Date":"30 Jul 2013 09:24 AM","Location":"Hauz Khas","Speed":42},{"Vehicle":"Honda CBR","Date":"30 Jul 2013 12:00 AM","Location":"Military Road","Speed":0},{"Vehicle":"Supra","Date":"30 Jul 2013 07:53 AM","Location":"Sec-45","Speed":58},{"Vehicle":"Land Cruiser","Date":"30 Jul 2013 09:35 AM","Location":"DLF Phase I","Speed":83}]</textarea>
    </div>
        <br>
    <h3><u>Click below button to download <strong>CSV</strong> file for internet explorer and other browsers</u></h3>
    <br>
    <button class="download">Download CSV</button>
    </div>
  </body>
</html>

 

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 &gt; 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 &lt; 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

 

About

Engineer. Blogger. I like to be updated on new upcoming emerging technologies.

Free PDF

Subscribe and get AngularJS Tips PDF. We never spam!
First Name:
Email:

73 comments

  1. burn
    |

    This is not working in IE11 .showing no error but still save as pop up is not coming.

    • |

      That its working fine , can you describe more on you problem.

      • Gaurav Dixit
        |

        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.

        • |

          Hi Gaurav,
          This is the only work-around that works for IE.

  2. bashi
    |

    The Demo does not work on IE9.

    • |

      Hi Bashi,
      Just now i have checked in IE9 and it’s working fine.
      Can you please describe more on you problem.

      • bashi
        |

        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.

  3. pss
    |

    Nothing happens when I click the ‘Download CSB’ in Safari. Any idea?

    • |

      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.

  4. |

    Extremely clever. I had csv downloading but could not figure out how to name the files.

  5. VJ
    |

    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.

    • |

      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.

  6. Khalid
    |

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

    • |

      We have used another approach because older version IE doesn’t allow to download CSV file.
      Thanks.

  7. |

    Hi, i tried on Safari 5.1.7 and it is not working. I looked in download location also but file is not present.

  8. chandni
    |

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

    • |

      Can you please describe more on your problem.

  9. Shakthi
    |

    Its not working on IE 11 with WPS Spreadsheet

    • |

      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.

  10. |

    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.

    • |

      Hi Robb,
      Ya you are right it wont work for that. this is a just basic example. There is one jquery plugin called papaparse – http://papaparse.com/ . Which will solve your problem.
      Thanks.

  11. nimesh
    |

    plz.. provide browser version support like http://caniuse.com/#feat=download.
    i have trouble to download csv from safari.
    i get error ‘undefined’ is not a function (evaluating : ‘link.click()’)

    • |

      Ya sure nimesh. Thanks for commenting. will surely update that soon. Also solve that problem as soon as possible.

  12. sarang sawant
    |

    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.

    • |

      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.

  13. |

    works like a charm.. spent half day on this issue. thanks a ton … 🙂

  14. Prashant
    |

    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

    • |

      Yes you are right.
      I am working on it. will solve as soon as possible.

      Thanks.

  15. perentti
    |

    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 ?

    • |

      Hi Perentti,

      Ya you are right. here in this tutorial i have shown another way to download csv files as older browser of IE doesn’t support download.
      Thanks.

  16. asutosh swain
    |

    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

    • |

      Hi asutosh,
      Just check whether you have added doctype at start of html page (i.e : < !DOCTYPE html>).
      all other things is perfect i guess. it should work.
      Thanks.

  17. Ray Mak
    |

    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/

    • |

      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.

  18. Enrique
    |

    Hi Inam,

    in ie 8.0 works fine?

    I’m trying to work in ie 8.0 but not is possible.

    Thanks in advance

    • |

      Hi Enrique,
      It work perfectly fine for me in IE 8.0. can you describe more on your problem so that i can help you.
      Thanks.

  19. Solo
    |

    Inaam, for me it says that “escape” is deprecated. How to use this line?

    • |

      Hi Solo,
      Can you please describe more on your problem. like browser along with it’s version so that i can help you with that.
      Thanks.

      • Amisha
        |

        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

        • |

          Hi Amisha,
          I am still working on it. will revert back to you, as soon as this problem resolved.
          Thanks.

  20. |

    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

    • |

      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

  21. Sandeep
    |

    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

    • |

      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.

      • rahul
        |

        in safari its not working…getting downloaded without file name and extension.
        can you tell some solution

        • |

          Hi Rahul,
          I am trying to resolve error for safari browser. will get back to you as soon as its done.
          Thanks.

  22. Satish Singampalli
    |

    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.

    • |

      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.

      • Satish
        |

        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.”

        • |

          Ok. so may the issue of data format. we need to check what kind of data needed for .xlsx file.

  23. Arat
    |

    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?

    • |

      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.

      • Arat
        |

        Thanks, but I am using IE 11. Could you please give me the other approach?

  24. Scott
    |

    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.

    • |

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

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

  25. Scott
    |

    Thank you, sir!

  26. San
    |

    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

    • |

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

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

      • Harish
        |

        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?

        • |

          Hi Harish,
          I checked and it’s work perfectly fine for me. can you please provide me more information so that i can help you with that.
          Thanks.

          • Sufyan Nisar
            |

            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.

          • |

            In which browser you facing this issue?

          • |

            Hey Inaam, just FYI this is a Safari 5 issue. While Blobs are – the Blob Constructor isn’t supported.

          • |

            Yes you are right Don. will find another way to resolve this problem and get back to you.
            thanks.

  27. Chakravarthy G
    |

    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

  28. farjana
    |

    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.

  29. vijay
    |

    Hi Innam,

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

    Thanks,
    Vijay

    • |

      Hi Vijay,
      I don’t see any ‘id’ column in downloaded file. can you please elaborate more so that we can get resolved.
      Thanks.

  30. Tarun
    |

    I cannot download it in IE edge

  31. |

    Can we somehow hide the data that gets written when new window opens, means by setting color to white or something ?

  32. |

    This code is only working in IE. I need export implementation in Microsoft Edge also. Can you please suggest, can you please update the code.

  33. |

    I got the solution for Microsoft edge:

    Use this code:

    var blob = new Blob( [ csvContent ], { type: “text/csv”} );
    navigator.msSaveOrOpenBlob( blob, fileName );

Leave a Comment