Last active
September 23, 2025 08:17
-
-
Save alekrutkowski/797ca03a87743ca6e25f5a27584f8b53 to your computer and use it in GitHub Desktop.
JavaScript function to fetch a CSV and put its rows into an array of objects, e.g. fetching data from Eurostat. Useful for feeding data into e.g. "Observable Framework" plots.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| async function fetchCSVtoObjects(url) { | |
| const response = await fetch(url); | |
| if (!response.ok) { | |
| throw new Error(`Failed to fetch CSV: ${response.status} ${response.statusText}`); | |
| } | |
| const text = await response.text(); | |
| const lines = text.trim().split(/\r?\n/); | |
| if (lines.length < 2) { | |
| return []; | |
| } | |
| // Helper to split a CSV line while respecting quotes | |
| function parseCSVLine(line) { | |
| const result = []; | |
| let current = ''; | |
| let insideQuotes = false; | |
| for (let i = 0; i < line.length; i++) { | |
| const char = line[i]; | |
| if (char === '"') { | |
| if (insideQuotes && line[i + 1] === '"') { | |
| // Escaped quote | |
| current += '"'; | |
| i++; | |
| } else { | |
| // Toggle insideQuotes | |
| insideQuotes = !insideQuotes; | |
| } | |
| } else if (char === ',' && !insideQuotes) { | |
| result.push(current); | |
| current = ''; | |
| } else { | |
| current += char; | |
| } | |
| } | |
| result.push(current); | |
| return result.map(v => v.trim()); | |
| } | |
| const headers = parseCSVLine(lines[0]); | |
| const data = lines.slice(1).map(line => { | |
| const values = parseCSVLine(line); | |
| const row = {}; | |
| headers.forEach((header, i) => { | |
| const value = values[i] ?? ""; | |
| const num = Number(value); | |
| row[header] = (value !== "" && !isNaN(num)) ? num : value; | |
| }); | |
| return row; | |
| }); | |
| return data; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: