gpt4 book ai didi

javascript - 如何使用javascript将大量json数据导出到CSV?

转载 作者:行者123 更新时间:2023-11-28 03:58:33 26 4
gpt4 key购买 nike

我尝试了下面的代码来导出,但如果 json 数据大小太大,它会在 Chrome 浏览器中给出错误(“失败 - 网络错误”)。对于小数据量,它工作得很好。

<script>
var items = [
{university: 'A',college: 'X',state: 'J'},
{university: 'B',college: 'Y',state: 'K'},
{university: 'C',college: 'Z',state: 'L'}
];

// Convert Object to JSON
var jsonObject = JSON.stringify(items);
var array = typeof jsonObject != 'object' ? JSON.parse(jsonObject) : jsonObject;
var csv = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
csv += line + '\r\n';
}
var uri = 'data:text/csv;charset=utf-8,' + csv;
data = encodeURI(uri);
var link = document.createElement("a");
link.href = data;
link.style = "visibility:hidden";
link.download = "xyz.csv";
link.click();
</script>

谢谢

最佳答案

对于大量数据尝试此操作

var items = [{
university: 'A',
college: 'X',
state: 'J'
},
{
university: 'B',
college: 'Y',
state: 'K'
},
{
university: 'C',
college: 'Z',
state: 'L'
}
];

// Convert Object to JSON
var jsonObject = JSON.stringify(items);
var array = typeof jsonObject != 'object' ? JSON.parse(jsonObject) : jsonObject;
var csv = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
csv += line + '\r\n';
}
csvData = new Blob([csv], {
type: "data:application/vnd.ms-excel;charset=utf-8,\uFEFF"
});
var csvUrl = URL.createObjectURL(csvData);
var a = document.createElement("a");
a.href = csvUrl;
a.setAttribute("download", fileName + ".csv");
document.body.appendChild(a);
a.click();

关于javascript - 如何使用javascript将大量json数据导出到CSV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47350699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com