Handle cast as undefineds
This commit is contained in:
parent
c87cc39cea
commit
650cbc1f01
|
@ -1,6 +1,19 @@
|
||||||
import csv from "csvtojson"
|
import csv from "csvtojson"
|
||||||
|
|
||||||
export async function jsonFromCsvString(csvString: string) {
|
export async function jsonFromCsvString(csvString: string) {
|
||||||
const result = await csv().fromString(csvString)
|
const castedWithEmptyStrings = await csv().fromString(csvString)
|
||||||
|
if (!castedWithEmptyStrings.length) {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
const emptyObject = Object.keys(castedWithEmptyStrings[0]).reduce(
|
||||||
|
(p, v) => ({ ...p, [v]: undefined }),
|
||||||
|
{}
|
||||||
|
)
|
||||||
|
|
||||||
|
let result = await csv({ ignoreEmpty: true }).fromString(csvString)
|
||||||
|
result = result.map(r => ({ ...emptyObject, ...r }))
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,6 +11,23 @@ describe("csv", () => {
|
||||||
{ id: "1", title: "aaa" },
|
{ id: "1", title: "aaa" },
|
||||||
{ id: "2", title: "bbb" },
|
{ id: "2", title: "bbb" },
|
||||||
])
|
])
|
||||||
|
result.forEach(r => expect(Object.keys(r)).toEqual(["id", "title"]))
|
||||||
|
})
|
||||||
|
|
||||||
|
test("empty values are casted as undefined", async () => {
|
||||||
|
const csvString =
|
||||||
|
'"id","optional","title"\n1,,"aaa"\n2,"value","bbb"\n3,,"ccc"'
|
||||||
|
|
||||||
|
const result = await jsonFromCsvString(csvString)
|
||||||
|
|
||||||
|
expect(result).toEqual([
|
||||||
|
{ id: "1", optional: undefined, title: "aaa" },
|
||||||
|
{ id: "2", optional: "value", title: "bbb" },
|
||||||
|
{ id: "3", optional: undefined, title: "ccc" },
|
||||||
|
])
|
||||||
|
result.forEach(r =>
|
||||||
|
expect(Object.keys(r)).toEqual(["id", "optional", "title"])
|
||||||
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
Loading…
Reference in New Issue