[英]Load JSON in d3.js to draw scatterplot
I am just trying my hand on d3.js and I am already in trouble.我只是在尝试 d3.js 并且我已经遇到了麻烦。 As per my knowledge, the second parameter passed in d3.json() can be used to process data from json.
据我所知,在 d3.json() 中传递的第二个参数可用于处理来自 json 的数据。
My code is:我的代码是:
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 };
}
In my code console.log(dataset) is giving me original JSON data rather than processed object returned by clean_data() function.在我的代码中,console.log(dataset) 给了我原始的 JSON 数据,而不是由 clean_data() function 返回的处理过的 object。
My JSON data look like this :我的 JSON 数据如下所示:
In my HTML for this, I have included CDN of d3.js:为此,在我的 HTML 中,我包含了 d3.js 的 CDN:
<script src="https://d3js.org/d3.v5.min.js"></script>
I am trying to make scatterplot from this JSON using d3.js and promise.我正在尝试使用 d3.js 和 promise 从这个 JSON 制作散点图。
You seems to have miss-understood how to use d3.json() , d3.json()
in v5 takes the first parameter URL and the second parameter is option object (since d3.json is a wrapper for fetch API ), which is the URL for your JSON server, then it will return a Promise fulfilled upon success and rejected upon failure, so you have to iterate over your JSON response and add it to an Array or maybe use the well known D3.js - enter(), update() and exit() pattern , here is an example of what you might do to get your data: You seems to have miss-understood how to use d3.json() ,
d3.json()
in v5 takes the first parameter URL and the second parameter is option object (since d3.json is a wrapper for fetch API ), which is the URL for your JSON server, then it will return a Promise fulfilled upon success and rejected upon failure, so you have to iterate over your JSON response and add it to an Array or maybe use the well known D3.js - enter(), update( ) 和 exit() 模式,以下是获取数据的示例:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.