javascript - 如何将 .CSV 文件解析为数组,以便在代码中进一步操作?
问题描述
我有兴趣从本地拥有的 .csv 文件中获取数据,将其作为字符串读取,然后将该字符串转换为数组。网上有很多关于类似过程的资料,但大多数指南都假定要操作的文件将作为程序的输入提供,而在我的情况下,我已经有数据并且需要它作为数组以便我可以使用它用于其他事情。我已经尝试操纵各种解决方案,以便他们做到这一点,但我无法完全弄清楚 - 下面的一个看起来很有希望(并且做了我想要做的)但我无法弄清楚如何将本地文件作为 FileReader 的输入:
<body>
<form id="myForm">
<input type="file" id="csvFile" accept=".csv" />
<br />
<input type="submit" value="Submit" />
</form>
<script>
const myForm = document.getElementById("myForm");
const csvFile = document.getElementById("csvFile");
function csvToArray(str, delimiter = ",") {
// slice from start of text to the first \n index
// use split to create an array from string by delimiter
const headers = str.slice(0, str.indexOf("\n")).split(delimiter);
// slice from \n index + 1 to the end of the text
// use split to create an array of each csv value row
const rows = str.slice(str.indexOf("\n") + 1).split("\n");
// Map the rows
// split values from each row into an array
// use headers.reduce to create an object
// object properties derived from headers:values
// the object passed as an element of the array
const arr = rows.map(function (row) {
const values = row.split(delimiter);
const el = headers.reduce(function (object, header, index) {
object[header] = values[index];
return object;
}, {});
return el;
});
// return the array
return arr;
}
myForm.addEventListener("submit", function (e) {
e.preventDefault();
const input = csvFile.files[0];
const reader = new FileReader();
reader.onload = function (e) {
const text = e.target.result;
const data = csvToArray(text);
document.write(JSON.stringify(data));
};
reader.readAsText(input);
});
</script>
</body
任何帮助将不胜感激 - 如果这不是很清楚,我很抱歉,我对此很陌生。理想情况下,我希望此代码将“MOCK_DATA.csv”之类的内容作为输入,而不是外部提供的输入。
解决方案
推荐阅读
- jboss - JBoss EAP 6.4.2 没有监听多个远程服务器
- cypress - 在多个“it”语句中使用变量来跟踪赛普拉斯的变化
- nginx - 如何使用ingress-nginx实现绝对路径转发请求
- python-3.x - 访问在多重继承中被覆盖的第二个父方法
- c# - 在这种情况下,一般异常处理不是那么糟糕吗?
- c - recvfrom() 没有收到完整的缓冲区
- bash - 检查 cron 语法以立即执行
- sql - 用 WHERE 子句划分 2 列
- python-3.x - python 3中的math.isnan,numpy.isnan和pandas.isnull有什么区别?
- spring-mvc - Spring Reactive 与 Spring MVC + MySQL 的集成