# Loading Data

#### d3_loading_data.html ● d3.min.js ● data/fruit.csv

### Loading data

D3 also allows us to load real data in various formats; in this tutorial we will use a .csv file.

D3 uses the Fetch-API which allows loading and parsing of data files such as CSV, JSON and TSV. This type of call returns a promise where the loaded data can be used after a .then(function(data){ }) function and the error handling can be done inside .catch(function(error){ })

d3.csv("fruit.csv")
.then(data => console.log(data))
.catch(error => console.log(error));

Note: The output will be in the console.

D3 loads data asynchronously, so that interaction with the browser is not hampered while loading (scripts not related to the data can still run in the meantime). To signal that the loading is complete, D3 calls the .then(data => { }) function. This is an important concept, as it means for developers that code which depends on the data should only exist inside the .then(data => { }) function.

### Converting data

D3 loads all our data as strings, so we have to convert it to numbers to work with it. This can be done with the "+" operator.

data.size = +data.size;

But as this has to be done for every item in the data set, you have to iterate over all items, either by using a loop or with the following statement:

data.forEach(d => d.size = +d["size"]);