Skip to content

Instantly share code, notes, and snippets.

@stekhn
Last active October 30, 2020 15:37
Show Gist options
  • Save stekhn/540f36e87c4f2a25823fbc7d2228d066 to your computer and use it in GitHub Desktop.
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.
// 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