Skip to content

Instantly share code, notes, and snippets.

@funkyremi
Created November 30, 2018 16:23
Show Gist options
  • Save funkyremi/c1ebd2e7a02efc93ddf41404d024f553 to your computer and use it in GitHub Desktop.
Save funkyremi/c1ebd2e7a02efc93ddf41404d024f553 to your computer and use it in GitHub Desktop.
Javascript csvToJson jsonToCsv
const jsonToCsv = (array, separator) => {
let result = '';
for (const key in array[0]) {
result.length === 0 ? result += key : result += `${separator}${key}`;
}
result += '\r\n';
array.forEach(line => {
let lineStr = '';
for (const value in line) {
lineStr.length === 0 ? lineStr += line[value] : lineStr += `${separator}${line[value]}`;
}
result += `${lineStr}\r\n`;
});
return result;
}
const csvToJson = (data, separator) => {
const csvArray = data.split('\r\n').filter(Boolean);
const keyNames = csvArray[0].split(separator);
const dataArray = csvArray.slice(1, csvArray.length - 1);
const result = [];
dataArray.forEach(d => {
let jsonEntryResult = {};
const entries = d.split(separator);
keyNames.forEach((keyName, idx) => {
jsonEntryResult[keyName] = entries[idx];
});
result.push(jsonEntryResult);
})
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment