2023-05-02 11:34:45 +02:00
|
|
|
import csv from "csvtojson"
|
|
|
|
|
|
|
|
export async function jsonFromCsvString(csvString: string) {
|
2023-05-02 13:46:53 +02:00
|
|
|
const castedWithEmptyValues = await csv({ ignoreEmpty: true }).fromString(
|
|
|
|
csvString
|
|
|
|
)
|
2023-05-02 12:57:18 +02:00
|
|
|
|
2024-10-31 18:16:06 +01:00
|
|
|
// By default the csvtojson library casts empty values as empty strings. This
|
|
|
|
// is causing issues on conversion. ignoreEmpty will remove the key completly
|
|
|
|
// if empty, so creating this empty object will ensure we return the values
|
|
|
|
// with the keys but empty values
|
2023-05-02 13:46:53 +02:00
|
|
|
const result = await csv({ ignoreEmpty: false }).fromString(csvString)
|
|
|
|
result.forEach((r, i) => {
|
2024-03-20 12:46:39 +01:00
|
|
|
for (const [key] of Object.entries(r).filter(([, value]) => value === "")) {
|
2023-05-02 13:46:53 +02:00
|
|
|
if (castedWithEmptyValues[i][key] === undefined) {
|
|
|
|
r[key] = null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2023-05-02 12:57:18 +02:00
|
|
|
|
2023-05-02 11:34:45 +02:00
|
|
|
return result
|
|
|
|
}
|