将JSON Parse Array转换为CSV

时间:2012-11-27 18:20:32

标签: php javascript json csv d3.js

首先,我看到了The Other Threads,我认为其中没有使用PHP或javascript。

我编码后添加了斜线以逃避JSON非法字符:

"#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12" "#Tahrir","2012-Oct-12"  "#Tahrir","2012-Oct-19" "#Tahrir","2012-Oct-19" "#Tahrir","2012-Oct-19"

想要将其更改为CSV或在此示例中找到与该图表一起使用的方法:http://bl.ocks.org/3883245#data.tsv

谢谢Inadvance。

1 个答案:

答案 0 :(得分:0)

要将json数据转换为CSV,请尝试使用此http://jsfiddle.net/sturtevant/vUnF9/(不是我的代码)

function JSON2CSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

var str = '';
var line = '';

if ($("#labels").is(':checked')) {
    var head = array[0];
    if ($("#quote").is(':checked')) {
        for (var index in array[0]) {
            var value = index + "";
            line += '"' + value.replace(/"/g, '""') + '",';
        }
    } else {
        for (var index in array[0]) {
            line += index + ',';
        }
    }

    line = line.slice(0, -1);
    str += line + '\r\n';
}

for (var i = 0; i < array.length; i++) {
    var line = '';

    if ($("#quote").is(':checked')) {
        for (var index in array[i]) {
            var value = array[i][index] + "";
            line += '"' + value.replace(/"/g, '""') + '",';
        }
    } else {
        for (var index in array[i]) {
            line += array[i][index] + ',';
        }
    }

    line = line.slice(0, -1);
    str += line + '\r\n';
}
return str;
}