这是一些将 csv 更改为 json 的代码(假设它支持名称的第一行)。您可以使用第一部分(array2d)并非常轻松地用它做其他事情。
// split rows by \r\n. Not sure if all csv has this, but mine did
const rows = rawCsvFile.split("\r\n");
// find all commas, or chunks of text in quotes. If not in quotes, consider it a split point
const splitPointsRegex = /"(""|[^"])+?"|,/g;
const array2d = rows.map((row) => {
let lastPoint = 0;
const cols: string[] = [];
let match: RegExpExecArray;
while ((match = splitPointsRegex.exec(row)) !== null) {
if (match[0] === ",") {
cols.push(row.substring(lastPoint, match.index));
lastPoint = match.index + 1;
}
}
cols.push(row.slice(lastPoint));
// remove leading commas, wrapping quotes, and unneeded \r
return cols.map((datum) =>
datum.replace(/^,?"?|"$/g, "")
.replace(/""/g, `\"`)
.replace(/\r/g, "")
);
})
// assuming first row it props name, create an array of objects with prop names of the values given
const out = [];
const propsRow = array2d[0];
array2d.forEach((row, i) => {
if (i === 0) { return; }
const addMe: any = {};
row.forEach((datum, j) => {
let parsedData: any;
if (isNaN(Number(datum)) === false) {
parsedData = Number(datum);
} else if (datum === "TRUE") {
parsedData = true;
} else if (datum === "FALSE") {
parsedData = false;
} else {
parsedData = datum;
}
addMe[propsRow[j]] = parsedData;
});
out.push(addMe);
});
console.log(out);