-
-
Save jonmaim/7b896cf5c8cfe932a3dd to your computer and use it in GitHub Desktop.
| // 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; | |
| } |
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
have bugs, and return [{"Header Name" :value, Header1 Name : value, ..]
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();
function csvTojs(csv) {
how to pass csv object to function?
Hello,
It's not working for me.
@hoist1999 could you provide the full code to fix it ?
Tks
what if the csv file is more than 1 GB