D3. Json Function to Return Only Some of Json File Data

I am reading csv file using d3.csv which works fine. Reading csv file also renames columns with a function:

However, I would rather read same data from a json file.

d3.csv("myfile.csv", function(d) {
    return {
        location: d.identifier,
        date: new Date(d.created),
        amount: d.count_objects
        };
}).then(function getData(rawData) {

    console.log(rawData[0]);        

});

The console output from d3.csv returns results with renamed columns:

console:

{location: "CO", date: Wed Jan 22 2020 00:00:00 GMT-0500 (Eastern Standard Time), amount: "0"}

I just swapped out csv for json file in same code, expecting it to be read similarly but it isn't.

d3.json("myfile.json", function(d) {
    return {
        location: d.identifier,
        date: new Date(d.created),
        amount: d.count_objects
        };
}).then(function getData(rawData) {

    console.log(rawData[0]);
    
});

However, the console output from d3.json returns results with orignal json keys:

console:

{created: "2020-01-22T00:00:00.000", identifier: "CO", count_objects: "0"}

What modifications are required for d3.json() to get same results with d3.csv() eg to return results with renamed keys?

1 Answer

d3.json doesn't use a row function, since json data isn't always an array. To processes the data, you can do something like:

d3.json("myfile.json").then(function (json) {
    return json.map(function (d) {
        return {
            location: d.identifier,
            date: new Date(d.created),
            amount: d.count_objects
        };
    });
}).then(function getData(rawData) {

    console.log(rawData[0]);
    
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest