D3.js Request Data — Loading CSV, JSON, and API Data
In this tutorial, you will learn about D3.js Request Data. We cover key concepts, practical examples, and best practices to help you master this topic.
D3.js request methods load external data from files and APIs using d3.csv, d3.json, d3.tsv, and d3.text, Parsing them into usable JavaScript arrays and objects.
What You'll Learn
By the end of this guide, you will load CSV and JSON files with D3, parse data types automatically, handle loading errors, load data from REST APIs, preprocess data before rendering, and chain multiple data loads.
Why Data Loading Matters
Hardcoded data works for demos. Real applications read from files and APIs. In Durga Antivirus Pro, the threat dashboard loads CSV logs of recent attacks and renders them as charts.
flowchart LR
A[CSV File] --> B[d3.csv]
C[JSON API] --> D[d3.json]
E[TSV File] --> F[d3.tsv]
B --> G[Parsed Data Array]
D --> G
F --> G
G --> H[Visualization]
Loading CSV Data
d3.csv('data/sales.csv').then(function(data) {
console.log(data);
console.log(data.columns);
// Create chart with data
});
// CSV file content:
// date,revenue,expenses
// 2024-01,15000,8000
// 2024-02,18000,8500
Expected output: An array of objects with properties date, revenue, and expenses. Revenue and expenses are strings unless parsed.
Loading JSON Data
d3.json('https://api.example.com/data').then(function(data) {
console.log(data);
}).catch(function(error) {
console.error('Failed to load:', error);
});
Parsing Data Types
d3.csv('data/sales.csv', function(d) {
return {
date: d3.timeParse('%Y-%m')(d.date),
revenue: +d.revenue,
expenses: +d.expenses,
profit: +d.revenue - +d.expenses
};
}).then(function(data) {
console.log(data);
});
Expected output: An array with proper Date objects, numeric values, and a computed profit field.
Loading Multiple Files
Promise.all([
d3.csv('data/revenue.csv'),
d3.json('data/expenses.json')
]).then(function(files) {
var revenueData = files[0];
var expensesData = files[1];
// Combine and render
});
Error Handling
d3.csv('data/missing-file.csv')
.then(function(data) {
if (data.length === 0) {
console.warn('No data found');
return;
}
renderChart(data);
})
.catch(function(error) {
console.error('Loading failed:', error);
d3.select('#chart')
.append('p')
.text('Failed to load data. Please try again.')
.style('color', 'red');
});
Common Mistakes
1. All Values Are Strings
D3.csv does not auto-parse numbers. Use the row conversion function or d3.autoType.
2. CORS Errors With External APIs
Browsers block cross-origin requests. Use a local proxy or load from the same origin.
3. Not Handling Empty Data
If the file is empty or has only headers, data is an empty array. Check length before processing.
4. Using .then Before Understanding Promises
d3.csv returns a Promise. Code after the .then does not wait for data. All data-dependent code must be inside .then.
5. File Path Issues
Relative paths are relative to the HTML file, not the JavaScript file. Use absolute paths or check the URL.
Practice Questions
Q1: What does d3.csv return? A: A Promise that resolves to an array of objects, one per row, with column headers as property names.
Q2: How do you parse numeric values from CSV?
A: Use the row conversion function: d3.csv('file.csv', function(d) { return { value: +d.value }; }).
Q3: What happens if the file does not exist? A: The Promise rejects. Use .catch() to handle the error.
Q4: How do you load multiple files sequentially? A: Use Promise.all() to load multiple files in parallel, or chain .then() calls for sequential loading.
Q5: What is d3.autoType? A: A function that automatically parses values as numbers, dates, or strings based on their format.
Challenge: Load a CSV of monthly sales data, parse dates and numbers, compute a rolling 3-month average, and render both the raw data and average as a combined line chart.
FAQ
Try It Yourself
Load a sample CSV and render a table.
<!DOCTYPE html>
<html>
<head>
<title>Data Loading Demo</title>
<style>
body { font-family: sans-serif; padding: 20px; }
table { border-collapse: collapse; width: 100%; max-width: 600px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background: #4ecdc4; color: white; }
tr:nth-child(even) { background: #f5f5f5; }
#status { margin: 10px 0; padding: 10px; border-radius: 6px; }
.loading { background: #fff3cd; color: #856404; }
.error { background: #f8d7da; color: #721c24; }
.success { background: #d4edda; color: #155724; }
</style>
</head>
<body>
<h2>CSV Data Loader</h2>
<div id="status" class="loading">Loading data...</div>
<div id="table-container"></div>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
var csvContent = `name,age,score
Alice,28,92
Bob,35,78
Charlie,22,95
Diana,31,88
Eve,29,91`;
d3.csv(URL.createObjectURL(new Blob([csvContent], { type: 'text/csv' })))
.then(function(data) {
var status = d3.select('#status');
status.text('Loaded ' + data.length + ' rows').attr('class', 'success');
var table = d3.select('#table-container')
.append('table');
table.append('thead').append('tr')
.selectAll('th').data(data.columns).enter()
.append('th').text(function(d) { return d; });
table.append('tbody')
.selectAll('tr').data(data).enter()
.append('tr')
.selectAll('td').data(function(row) {
return data.columns.map(function(col) { return row[col]; });
}).enter()
.append('td').text(function(d) { return d; });
})
.catch(function(err) {
d3.select('#status')
.text('Error: ' + err.message)
.attr('class', 'error');
});
</script>
</body>
</html>
What's Next
Localize and format data for different locales.
Localization — Locale-aware formatting in D3.js. Responsive — Responsive D3.js visualizations.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro