Skip to content

Instantly share code, notes, and snippets.

@jonmaim
Last active November 23, 2020 11:00
Show Gist options
  • Save jonmaim/7b896cf5c8cfe932a3dd to your computer and use it in GitHub Desktop.
Save jonmaim/7b896cf5c8cfe932a3dd to your computer and use it in GitHub Desktop.
Function takes a CSV (header + data) string as input and gives back a JS object.
// Start from https://gist.github.com/iwek/7154578#file-csv-to-json-js
// and fix the issue with double quoted values
function csvTojs(csv) {
var lines=csv.split("\n");
var result = [];
var headers = lines[0].split(",");
for(var i=1; i<lines.length; i++) {
var obj = {};
var row = lines[i],
queryIdx = 0,
startValueIdx = 0,
idx = 0;
if (row.trim() === '') { continue; }
while (idx < row.length) {
/* if we meet a double quote we skip until the next one */
var c = row[idx];
if (c === '"') {
do { c = row[++idx]; } while (c !== '"' && idx < row.length - 1);
}
if (c === ',' || /* handle end of line with no comma */ idx === row.length - 1) {
/* we've got a value */
var value = row.substr(startValueIdx, idx - startValueIdx).trim();
/* skip first double quote */
if (value[0] === '"') { value = value.substr(1); }
/* skip last comma */
if (value[value.length - 1] === ',') { value = value.substr(0, value.length - 1); }
/* skip last double quote */
if (value[value.length - 1] === '"') { value = value.substr(0, value.length - 1); }
var key = headers[queryIdx++];
obj[key] = value;
startValueIdx = idx + 1;
}
++idx;
}
result.push(obj);
}
return result;
}
@hafizaarif
Copy link

hafizaarif commented Jul 27, 2016

what if the csv file is more than 1 GB

@zanonnicola
Copy link

You can use a dedicated Web Worker for that operation: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

@vitaliyKorzhenko
Copy link

have bugs, and return [{"Header Name" :value, Header1 Name : value, ..]

@hoist1999
Copy link

There is a bug:
var value = row.substr(startValueIdx, idx - startValueIdx).trim();
In the condition 'idx === row.length - 1', value lost a character.

I fix this bug:
if (c === ',' || /* handle end of line with no comma / idx === row.length - 1) {
let length = idx - startValueIdx;
if(idx === row.length -1) {
length++;
}
/
we've got a value */
var value = row.substr(startValueIdx, length).trim();

@rohinioup
Copy link

function csvTojs(csv) {
how to pass csv object to function?

@Maxime936
Copy link

Hello,
It's not working for me.
@hoist1999 could you provide the full code to fix it ?

Tks

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