<! DOCTYPE html> [ { "Login_time": "19720", "user_id": "296480061832316496" }]</textarea> <button class= ' gen_btn ' >generate file</button></div><script>$ (document). Ready (function(){ $(' button '). Click (function(){ varData = $ (' #txt '). Val (); if(Data = = ") return; Jsontocsvconvertor (data,"Vehicle Report",true); }); }); functionJsontocsvconvertor (Jsondata, Reporttitle, ShowLabel) {//If Jsondata is not a object then Json.parse would parse the JSON string in an object varArrdata =typeofJsondata! = ' object '?Json.parse (jsondata): Jsondata; varCSV = "; //Set report title on first row or lineCSV+ = Reporttitle + ' \r\n\n '; //This condition'll generate the Label/header if(ShowLabel) {varrow = ""; //This loop would extract the label from 1st Index of an on array for(varIndexinchArrdata[0]) { //Now convert each value to string and comma-sepratedRow + = index + ', '; } row= Row.slice (0,-1); //append Label row with line breakCSV + = row + ' \ r \ n '; } //1st Loop is to extract each row for(vari = 0; i < arrdata.length; i++) { varrow = ""; //2nd loop would extract each column and convert it in string comma-seprated for(varIndexinchArrdata[i]) {Row+ = ' + ' + Arrdata[i][index] + "+ '", '; } row.slice (0, Row.length-1); //Add a line break after each rowCSV + = row + ' \ r \ n '; } if(CSV = = ") {alert ("Invalid Data"); return; } //Generate a file name varFileName = "Myreport_"; //This would remove the blank-spaces from the title and replace it with an underscoreFileName + = Reporttitle.replace (//g, "_");//Initialize file format you want CSV or XLS varURI = ' Data:text/csv;charset=utf-8, ' +Escape (CSV); //Now the little tricky part. //You can use either>> window.open (URI); //But this would not be work in some browsers //Or you'll not get the correct file extension //This trick would generate a temp <a/> tag varlink = document.createelement ("a"); Link.href=URI; //set the visibility hidden so it won't effect on your web-layoutLink.style = "Visibility:hidden"; Link.download= FileName + ". csv"; //This part would append the anchor tag and remove it after automatic clickdocument.body.appendChild (link); Link.click (); Document.body.removeChild (link); }</script></body>Transferred from: http://jsfiddle.net/hybrid13i/JXrwM/
Web-side, JSON-directed CSV file