【问题标题】:Load JSON in d3.js to draw scatterplot在 d3.js 中加载 JSON 以绘制散点图
【发布时间】:2020-05-06 11:56:56
【问题描述】:

我只是在尝试使用 d3.js,但我已经遇到了麻烦。 据我所知,传入d3.json()的第二个参数可以用来处理来自json的数据。

我的代码是:

 d3.json(base_url() + "data/data.json", clean_data)
   .then(function (dataset) {
      global_dataset = dataset;
      console.log(dataset.age);
  })
 .catch(() => console.log("could not load a file"));

function clean_data(d) {
 console.log("i am here");
 let balance = d.balance;
 balance = balance.splice(1);
 return { age: +d.age, balance: +balance };
}

在我的代码中,console.log(dataset) 给了我原始 JSON 数据,而不是 clean_data() 函数返回的已处理对象。

我的 JSON 数据如下所示

JSON URL

在我的 HTML 中,我已经包含了 d3.js 的 CDN:

   <script src="https://d3js.org/d3.v5.min.js"></script>

我正在尝试使用 d3.js 和 promise 从这个 JSON 中制作散点图。

【问题讨论】:

  • “据我所知,d3.json()中传入的第二个参数可以用来处理来自json的数据”。不,这是不正确的,d3.json 不接受行函数。

标签: javascript json d3.js


【解决方案1】:

您似乎没有理解如何使用d3.json(),v5 中的d3.json() 采用第一个参数URL 和second parameter is option object(因为d3.json 是fetch API 的包装器),即URL对于您的 JSON 服务器,那么它将返回一个 Promise 在成功时完成并在失败时拒绝,因此您必须遍历您的 JSON 响应并将其添加到数组中,或者使用众所周知的 D3.js - enter(), update() and exit() pattern,下面是一个示例,说明您可能会采取哪些措施来获取数据:

const data = [];

d3.json('https://next.json-generator.com/api/json/get/V1OqfcoK_')
 .then(function (dataset) {
   dataset.forEach((d, i) => {
     data.push({age: +d.age, balance: +Number(d.balance.replace(/[^0-9.-]+/g, ""))});
   });
   // once done iterating over dataset we can use it
   console.log(data);
})
.catch(() => console.log("could not load a file"));
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v5.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 2015-01-13
    • 1970-01-01
    • 2021-07-02
    • 2014-05-25
    • 2013-05-18
    • 2018-08-15
    相关资源
    最近更新 更多