Last active
August 28, 2016 06:29
-
-
Save ajliv/64e5e32214d4f9c2ff6b22a95f66cf4d to your computer and use it in GitHub Desktop.
Convert a JSON object to CSV
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
import { flatten, keys, startCase, uniq } from 'lodash'; | |
const json2csv = (rows = []) => { | |
const columns = parseCSVColumns(rows); | |
return [parseCSVHeaders(columns), ...rows.map(row => parseCSVRow(row, columns))].join('\n'); | |
}; | |
const escapeCSVString = (str = '') => { | |
const value = str ? JSON.parse(JSON.stringify(str)) : ''; | |
return `"${value.replace(/(\r\n|\n|\r)/gm, '').replace(/"/g, '"""')}"`; | |
}; | |
const parseCSVColumns = (rows) => uniq(flatten(rows.map(keys))); | |
const parseCSVHeaders = (columns) => columns.map(column => `"${startCase(column)}"`).join(','); | |
const parseCSVRow = (row, columns) => columns.map(key => escapeCSVString(row[key])).join(','); | |
export default json2csv; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment