Skip to content

Instantly share code, notes, and snippets.

@khaledosman
Last active August 25, 2021 14:16
Show Gist options
  • Save khaledosman/9d254937381272ff4173048442b1d396 to your computer and use it in GitHub Desktop.
Save khaledosman/9d254937381272ff4173048442b1d396 to your computer and use it in GitHub Desktop.
helper file to write json data in csv format
function constructCSVFromJSON (json, columns, separator = ',') {
const header = columns.join(separator) + '\n'
let body = ''
if (Array.isArray(json)) {
body = json.reduce((accum, result) => accum + createRowFromJSON(columns, result, separator), '')
} else {
body = createRowFromJSON(columns, json, separator)
}
return header + body
}
function createRowFromJSON (columns, json, separator = ',') {
return columns.map(key => json[key]).join(separator) + '\n'
}
function constructJSONFromCSV (csv, separator = ',') {
const rows = csv.split('\n').map(row => row.trim())
const columns = rows[0].split(separator)
const body = rows.slice(1, rows.length)
return body.map(row => createJSONFromRow(columns, row, separator))
}
function createJSONFromRow (columns, row, separator = ',', quoteChar = '"') {
// sometimes the row can have `""` inside which breaks splitting by comma
const regex = new RegExp(`\\s*(${quoteChar})?(.*?)\\1\\s*(?:${separator}|$)`, 'gs')
const values = row.match(regex).filter(Boolean)
return values.map((value, index) => {
return {
[columns[index]]: value
}
})
.reduce((accum, item) => ({ ...accum, ...item }), {})
}
module.exports = { constructCSVFromJSON, constructJSONFromCSV }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment