首页 > 解决方案 > D3.json函数只返回部分json文件数据

问题描述

我正在阅读 csv 文件,使用d3.csv它可以正常工作。读取 csv 文件还会使用函数重命名列:

但是,我宁愿从 json 文件中读取相同的数据。

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]);        

});

控制台输出d3.csv返回带有重命名列的结果:

console:

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

我只是用相同的代码将 csv 换成 json 文件,希望它被类似地读取,但事实并非如此。

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]);
    
});

但是,控制台输出d3.json返回带有原始 json 键的结果:

console:

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

需要进行哪些修改d3.json()才能获得相同的结果,d3.csv()例如使用重命名的键返回结果?

标签: javascriptd3.js

解决方案


d3.json不使用行函数,因为 json 数据并不总是一个数组。要处理数据,您可以执行以下操作:

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]);
    
});

推荐阅读