Loading Data Externally

We'll look at how we can load data from external resources.

We are going to learn about how to make requests with D3. It is the final fundamental concept we will learn before jumping into creating graphs. Data is not always available in our script. We may need to grab data from an external resource.

Generally speaking, there are three possible locations where your data can come from. Data can be hardcoded in a JavaScript file. We can store data in files such as JSON or CSV files. Lastly, we can grab data from an API resource.

The most common location to store data is in a file. The two most common formats for storing data are JSON and CSV files. We can also grab data from a text or XML file. For this course, we will be focusing on the two most popular formats, JSON and CSV.

D3 fetch

The D3 fetch package is responsible for handling HTTP requests. You can find more information about this package here.

This library contains a set of functions for performing HTTP requests. Under the hood, it uses the fetch() JavaScript function. It builds upon this function by providing a simpler API. It is capable of parsing data from a request. This makes our code more readable.

However, you do not need to use the D3 fetch functions. They are entirely optional. If you have another library you prefer for making requests, then, by all means, use it. By default, the D3 fetch library is included with the full version of D3. We don’t need to do anything to install it.

Let’s get started with this library. We are going to look at how we can request a JSON file. For these examples, we will be working on a new project.

JSON

JSON is a format for storing data. The syntax for JSON is the same syntax for objects and arrays in JavaScript. For this example, we will have a separate file called data.json.

If you are on Educative, the link to this file is the following: https://www.educative.io/udata/4zEpr2Mxkvo/data-3-13.json

If you are working locally, save this file as data.json and store it with your project.

Inside this file, we will find an array with the numbers 10, 20, 30, 40, and 50. It is a very basic example. The goal is to load this file into our project. We can use D3 to perform the request for this file. In our script file, we are going to call the d3.json() function.

Get hands-on with 1200+ tech skills courses.