Last active
October 30, 2020 15:37
-
-
Save stekhn/540f36e87c4f2a25823fbc7d2228d066 to your computer and use it in GitHub Desktop.
Converts JSON to a CSV string. Only works with a one-dimensional JavaScript array of one-dimensional objects.
This file contains hidden or 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
// Convert JSON to a CSV string | |
function jsonToCsv(json) { | |
const replaceEmpty = (key, value) => { | |
return value === null ? '' : value; | |
}; | |
const parseRow = row => { | |
return header.map(fieldName => | |
JSON.stringify(row[fieldName], replaceEmpty) | |
).join(','); | |
}; | |
const header = Object.keys(json[0]); | |
const rows = json.map(parseRow); | |
const rowsWithHeader = [header.join(','), ...rows]; | |
const csv = rowsWithHeader.join('\r\n'); | |
return csv; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment