Created
March 24, 2024 12:07
-
-
Save ahallora/44727c7c0a0f9e9d743e327fccaa2ca9 to your computer and use it in GitHub Desktop.
Convert csv to JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const parseCSVLine = (line: string): string[] => { | |
const parts = line.split(","); | |
const result: string[] = []; | |
parts.reduce( | |
(accumulator, currentPart) => { | |
if (!accumulator.insideQuotes) { | |
if (currentPart.startsWith('"') && currentPart.endsWith('"')) { | |
// Handle the case when the value is enclosed in double quotes | |
result.push(currentPart.slice(1, -1)); | |
} else if (currentPart.startsWith('"')) { | |
accumulator.insideQuotes = true; | |
accumulator.current += currentPart.slice(1) + ","; | |
} else { | |
result.push(currentPart); | |
} | |
} else { | |
if (currentPart.endsWith('"')) { | |
accumulator.insideQuotes = false; | |
accumulator.current += currentPart.slice(0, -1); | |
result.push(accumulator.current); | |
accumulator.current = ""; | |
} else { | |
accumulator.current += currentPart + ","; | |
} | |
} | |
return accumulator; | |
}, | |
{ current: "", insideQuotes: false } | |
); | |
return result; | |
}; | |
export const csvToJson = (csv: string) => { | |
if (!csv || !csv.includes("\n")) return []; | |
const lines = csv.trim().split("\n"); | |
const headers = lines.shift()?.split(",") ?? []; | |
return lines.map((line) => { | |
const values = parseCSVLine(line); | |
return headers.reduce((obj, header, index) => { | |
const value = values[index] ?? ""; | |
obj[header] = value.endsWith(",") | |
? value.substring(0, value.length - 1) | |
: value; | |
return obj; | |
}, {}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment