How to Get json Data with D3

How to Get json Data with D3

Once you have set up d3 and webpack, and then you have set a webpack hot module replacement (hmr), you should try to use d3 to get data from a .json file.

You’ll first need a .json file. If you don’t have one already, you can create one on https://www.mockaroo.com/. Set the number of rows to 4, the file type to JSON, and select “array” as an option. That is what I did, and the dummy data ended up looking like this:

[{
        "id": 1,
        "first_name": "Hadria",
        "last_name": "Essberger",
        "email": "[email protected]",
        "gender": "Female"
    },
    {
        "id": 2,
        "first_name": "Wendel",
        "last_name": "Lawton",
        "email": "[email protected]",
        "gender": "Male"
    },
    {
        "id": 3,
        "first_name": "Ardenia",
        "last_name": "Pavett",
        "email": "[email protected]",
        "gender": "Female"
    },
    {
        "id": 4,
        "first_name": "Wakefield",
        "last_name": "Maylott",
        "email": "[email protected]",
        "gender": "Male"
    }
]

I put this in a file here: /dist/data/MOCK_DATA.json (see previous posts linked above for context).

Then I put this code inside of my src/index.js file:

import * as d3 from 'd3';

export function get_data() {
    d3.json("./data/MOCK_DATA.json").then(function(data) {
        data.forEach(function(item) {
            document.write(item.first_name + '<br>');
          });
    });
}

This prints out the first_name field of all 4 items in the data.

1 thought on “How to Get json Data with D3”

Leave a Comment