Skip to content

Instantly share code, notes, and snippets.

@Krinkle
Forked from codepo8/CSVtoJSon.js
Last active February 29, 2024 06:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Krinkle/45fad2ceefdaabfa8f589c484495353e to your computer and use it in GitHub Desktop.
Save Krinkle/45fad2ceefdaabfa8f589c484495353e to your computer and use it in GitHub Desktop.
OK, here is my function to turn CSV into JSON - what's yours?
const csvToJSON = (csv) => {
const getcsvdata = (csv) => {
const csvRegex = /,(?=(?:(?:[^"]*"){2})*[^"]*$)/;
const trimQuotes = /^"|"$/g;
csv = csv.split(csvRegex).map(
h => h.trim().replace(trimQuotes, '')
);
return csv;
}
let lines = csv.split('\n');
let headers = getcsvdata(lines.shift());
let result = [];
for (let line of lines) {
let currentline = getcsvdata(line);
result.push(headers.reduce((item, header, i) => {
item[header] = currentline[i];
return item;
}, {}));
}
return result;
}

Size: 224 bytes

let csvToJSON=e=>{let t=e=>e=e.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/).map(e=>e.trim().replace(/^"|"$/g,"")),l=e.split("\n"),r=t(l.shift()),p=[];for(let e of l){let l=t(e);p.push(r.reduce((e,t,r)=>(e[t]=l[r],e),{}))}return p};

As minified by SWC 1.3.100 using settings:

  • Target: ES2022
  • Source: Unknown
  • Minify: Yes (Defaults)
  • Compress: Yes (Defaults + unsafe_regexp)
  • Mangle: Yes (Defaults)

Permalink

let csv = `Name, Age, City
John, 21, New York
"Jane, Doe", 22, San Francisco
Jim, 23, Chicago
"Jill Chill", 24, "Tacoma, Seattle"`;
console.log(csvToJSON(csv));
@codepo8
Copy link

codepo8 commented Feb 29, 2024

Like the line shift. :)

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