js json转csv

Posted simple_孙

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js json转csv相关的知识,希望对你有一定的参考价值。

$(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 + ‘
‘;
            }
            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 + ‘
‘;
            }
            if (CSV == ‘‘) {
                growl.error("Invalid data");
                return;
            }
            var fileName = "Result";
            if (mo.msieversion()) {
                var IEwindow = window.open();
                IEwindow.document.write(‘sep=,
‘ + 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();

});

另一种

下载的的方法是构建Url

data:text/csv;charset=UTF-8,Base32编码的csv字符串。

 

限制:

谷歌浏览器和IE浏览器对Url的最大长度限制不一样,总的来说,在前端组建CSV适用性非常有限,而且存在兼容性问题,不推荐使用。

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
    var arrData = typeof JSONData != ‘object‘ ? JSON.parse(JSONData) : JSONData;
    var CSV = "ufeff";
    var firfixCSV = "ufeff";
    if (ShowLabel) {
        var row = "";
        var firfixRow = "";
        for (var index in arrData[0]) {
            row += index + ‘,‘;
            firfixCSV += index + ‘,‘;
        }
        CSV += row.slice(0, -1) + ‘
‘;
        firfixCSV = (firfixCSV.slice(0, -1) + ‘
‘);
    }
    for (var i = 0; i < arrData.length; i++) {
        var row = "";
        for (var index in arrData[i]) {
            row += ‘"‘ + arrData[i][index] + ‘",‘;
            firfixCSV += arrData[i][index] + ‘,‘;
        }
        row.slice(0, row.length - 1);
        CSV += row + ‘
‘;
        firfixCSV = (firfixCSV.slice(0, -1) + ‘
‘);
    }

    if (CSV == ‘‘) {
        alert("Invalid data");
        return;
    }
    var link = document.createElement("a");
    link.id = "lnkDwnldLnk";
    document.body.appendChild(link);
    var csv = CSV;
    blob = new Blob([csv], { type: ‘text/csv,charset=UTF-8‘, endings: ‘native‘ });
    if (window.webkitURL) {
        var csvUrl = window.webkitURL.createObjectURL(blob);
    } else {
        var csvUrl = ‘data:text/csv;charset=UTF-8,ufeff‘ + encodeURIComponent(firfixCSV);
    }
    var filename = ReportTitle + ‘.csv‘;
    $("#lnkDwnldLnk")
    .attr({
        ‘download‘: filename,
        ‘href‘: csvUrl
    });
    $(‘#lnkDwnldLnk‘)[0].click();
    $(‘.bs-example-modal-lg‘).modal(‘hide‘);
    document.body.removeChild(link);
}

 

以上是关于js json转csv的主要内容,如果未能解决你的问题,请参考以下文章

实用代码片段将json数据绑定到html元素 (转)

JSON字符串转实体对象

怎么把json字符串转成数组对象

如何用原生JS来把JSON数据处理成CSV格式

如何将json的数据转化成csv的数据格式

python将json转csv