简体   繁体   English

在 D3 中使用自己的 JSON 数据

[英]Using own JSON data in D3

I am following this d3.js example.我正在关注这个d3.js示例。

The data in this example is a csv file with the following structure:本例中的数据是一个csv文件,结构如下:

name姓名 code代码 pop流行音乐
Albania阿尔巴尼亚 ALB ALB 3153731 3153731
United States美国 USA美国 299846449 299846449
Great Britain大不列颠 GBR GBR 60244834 60244834

The data is loaded this way:数据以这种方式加载:

.defer(d3.csv, "https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world_population.csv", function(d) { data.set(d.code, +d.pop); })

Now I am trying to use my own modified data in JSON format.现在我正在尝试使用我自己修改的 JSON 格式的数据。

test.json

 [{
        "name": "Albania",
        "code": "ALB",
        "pop": "0.111"
    },

    {
        "name": "United States",
        "code": "USA",
        "pop": "0.222"
    },
    {
        "name": "Great Britain",
        "code": "GBR",
        "pop": "0.333"
    }
 ]

To do this I just load my data instead of the dummy data:为此,我只加载我的数据而不是虚拟数据:

var test = "test.json"

.defer(d3.json, test , function(d) { data.set(d.code, +d.pop);})

If I console.log the csv and the json , the resulting Objects look exactly the same.如果我console.log csvjson ,生成的对象看起来完全一样。 But with the json no map is loaded and with the csv the map is loaded.但是使用json没有加载 map 并且使用csv加载了 Z1D78DC8ED51214E518B5114AE24490。

When I console.log the csv data like this:当我console.log csv数据时,如下所示:

.defer(d3.csv,  "https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world_population.csv", function(d) { console.log("DATA : " , d.code)
  data.set(d.code, +d.pop);})

I see the values in the code column in the console.我在控制台的code列中看到了值。

If I do the same with the json :如果我对json做同样的事情:

.defer(d3.json, test, function(d) { console.log("DATA : " , d.code)
    data.set(d.code, +d.pop);})

Nothing appears in the console.控制台中不显示任何内容。

So my question is, why can I access the values in the csv with d.code and d.pop , but not in the json ?所以我的问题是,为什么我可以使用d.coded.pop访问csv中的值,但不能访问json中的值?

I found out what I was doing wrong.我发现我做错了什么。

I cant use this part:我不能使用这部分:

defer(d3.json, test, function(d) { console.log("DATA : " , d.code)
    data.set(d.code, +d.pop);})

Because I cant use a row function with d3.json .因为我不能将一行 function 与d3.json一起使用。

More information in this question问题中的更多信息

It seems to be that d in defer(d3.json, test, function(d) { is an array.似乎defer(d3.json, test, function(d) { d的 d 是一个数组。

Try the following:尝试以下操作:

.defer(d3.json, test , function(d) { 
  d.forEach(({code, pop}) => data.set(code, +pop));
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM