Skip to content

Instantly share code, notes, and snippets.

@iwek
Last active July 5, 2024 14:29
Show Gist options
  • Save iwek/7154578 to your computer and use it in GitHub Desktop.
Save iwek/7154578 to your computer and use it in GitHub Desktop.
CSV to JSON Conversion in JavaScript
//var csv is the CSV file with headers
function csvJSON(csv){
var lines=csv.split("\n");
var result = [];
var headers=lines[0].split(",");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
//return result; //JavaScript object
return JSON.stringify(result); //JSON
}
@waicampos
Copy link

@OFRBG I liked this your solution. I suggest just filtering the lines before iteration to eliminate blank lines from the csv file.

const csvToJson = csv => {
  const [firstLine, ...lines] = csv.split('\n');
  const keys = firstLine.split(',');
  // add a filter here
  return lines.filter(line => line).map(line => ((values) => 
    keys.reduce(
      (curr, next, index) => ({
        ...curr,
        [next]: values[index],
      }),
      {}
    )
  )(line.split(',')));
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment