【问题标题】:Access nested JSON with d3.json()使用 d3.json() 访问嵌套的 JSON
【发布时间】:2014-08-15 07:43:39
【问题描述】:

我有以下 JSON

{
    "users":
 {
     "gender":
  {
      "tot":
   [
       {"label":"female", "value":6038},
       {"label":"male", "value":45228},
       {"label":"unknown", "value":32932}
   ]
  }
 }
}

我可以使用d3.json() 加载文件并通过console.log() 将其可视化,但我无法访问内部值和标签

请考虑以下脚本

d3.json("../data/m5s/sumStats.json", function(data) {
    console.log(data)
    x.domain(data.map(function(d) {
        return d[0].users[0].gender[0].comment[0].label;
    }));
});

在第三行返回

Uncaught TypeError: undefined is not a function 

【问题讨论】:

  • 您的标签访问代码与您的对象定义不匹配。除此之外,x 是在哪里定义的?
  • 对象没有可用的map 方法。因此,调用data.map() 将产生“TypeError: undefined is not a function”。

标签: javascript json d3.js


【解决方案1】:

您可以使用纯对象表示法访问数据:

d3.json("../data/m5s/sumStats.json", function(data) {
    // these are just examples, you don't need them
    console.log(data);
    console.log(data.users);
    console.log(data.users.gender);
    console.log(data.users.gender.tot);

    // this is the important bit: we're not going over 'data' but over a sub-object of data:
    x.domain(data.users.gender.tot.map(function(d) { return d.label; }));
});

【讨论】:

  • 这可能是一个完全不同的排序问题,但如果我有不同的嵌套对象,我想在不同的图表中用@ 可视化(...gender.tot1、gender.tot2、gender.tot3 等) 987654325@ 最佳实践是什么?我应该使用 data1 = d3.json("../data/m5s/sumStats.json", function(data.users.gender.tot1) {return data;}); 将它们加载到不同的变量中吗?
  • 您可以在所有键上使用 for ... in 循环。在您的情况下,可能如下所示:for (var key in data.users.gender) { console.log("this is your key: ", key); console.log("it contains: ", data.users.gender[key]); } - 抱歉,cmets 中没有缩进。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 2013-11-18
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多