Skip to content

Instantly share code, notes, and snippets.

@rik
Forked from codepo8/CSVtoJSon.js
Last active February 29, 2024 09:12
Show Gist options
  • Save rik/c45d2eec52ebfb78be5f5eedeb0ea617 to your computer and use it in GitHub Desktop.
Save rik/c45d2eec52ebfb78be5f5eedeb0ea617 to your computer and use it in GitHub Desktop.
OK, here is my function to turn CSV into JSON - what's yours?
function _csvRowToArray(csv) {
const csvRegex = /,(?=(?:(?:[^"]*"){2})*[^"]*$)/
const trimQuotes = /^"|"$/g
return csv.split(csvRegex).map(h => h.trim().replace(trimQuotes, ''))
}
function _csvRowToObject(headers, row) {
let currentRow = _csvRowToArray(row)
return Object.fromEntries(headers.map((header, i) => [header, currentRow[i]]))
}
function csvToJSON(csv) {
const [headersRow, ...rows] = csv.split('\n')
let headers = _csvRowToArray(headersRow)
return rows.map(row => _csvRowToObject(headers, row))
}
let csv = `Name, Age, City
John, 21, New York
"Jane, Doe", 22, San Francisco
Jim, 23, Chicago
"Jill Chill", 24, "Tacoma, Seattle"`
console.log(csvToJSON(csv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment