服务器之家

服务器之家 > 正文

使用javascript实现json数据以csv格式下载

时间:2021-06-26 17:15     来源/作者:JavaScript教程网

摘要:
  最近有一个非项目的小需求,就是将项目开发分工文件化,方便后期管理维护。但是开发时,分工安排都是以json格式记录的,所以就做了一个将json数据以csv格式下载到本地。

代码:

 

复制代码 代码如下:

<!DOCTYPE html>
<html>
    <title>download csv</title>
    <head>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
        <script type="text/javascript" src="download.js"></script>
    </head>
    <body>
        <div align="center">
            <h3><u>Enter JSON data</u></h3>
            <div class='mydiv'>
                    <textarea id="txt" class='txtarea' rows="15" cols="100">[{"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/>
            <button class="download">Download CSV</button>
        </div>
    </body>
</html>

 

download.js

 

复制代码 代码如下:

$(document).ready(function() {
    "use strict";
    var mo = {
        init: function() {
            $('.download').click(function() {
                var data = $('#txt').val();
                if (data === '') {
                    return;
                }
                mo.JSONToCSVConvertor(data, true);
            });
        },
        JSONToCSVConvertor: function(JSONData, 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 (mo.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);
            }
        },
        msieversion: function() {
            var ua = window.navigator.userAgent;
            var msie = ua.indexOf("MSIE ");
            if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
            {
                return true;
            } else { // If another browser,
                return false;
            }
            return false;
        },
        main: function() {
            mo.init();
        }
    };
    mo.main();
});

 

小结:
  注意json格式[{},{}],文件名是在js中定义的变量fileName。主要问题是他会自动添加一行空行,且每个元素都会在值前面加个'='。

下载下来的数据格式为:

使用javascript实现json数据以csv格式下载

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部