【问题标题】:Nested JSON Objects with Dimple.js使用 Dimple.js 嵌套 JSON 对象
【发布时间】:2015-08-20 19:20:44
【问题描述】:

我正在尝试使用 Dimple.JS 和 D3 创建堆积条形图。但是,我希望在此特定可视化中使用的 JSON 文件涉及嵌套的 JSON 对象(如下)。我希望创建的堆叠条形图将通道类别作为其 x 轴,y 轴作为不同位置的总计数(每个位置作为“堆栈”)。这是原始数据:

[{
    "channel": "politics",
    "locations": 
    [{
        "name":"usa", 
        "count" : 1454
        },
    {
        "name":"mexico",
        "count":3543
        },
    {
        "name":"antarctica",
        "count":4352
    }]
},
{
    "channel": "economics",
    "locations": 
    [{
        "name":"usa", 
        "count" : 12431
        },
    {
        "name":"mexico",
        "count":314
        },
    {
        "name":"china",
        "count":2321
        }]
}]

我已将上面的内容扁平化为下面的 JSON,但我在使用 Dimple 的 .addSeries() 方法创建堆栈时遇到了问题。

[
{
    "channel": "politics",
    "locations[0].name": "usa",
    "locations[0].count": 1454,
    "locations[1].name": "mexico",
    "locations[1].count": 3543,
    "locations[2].name": "antarctica",
    "locations[2].count": 4352
},
{
    "channel": "economics",
    "locations[0].name": "usa",
    "locations[0].count": 12431,
    "locations[1].name": "mexico",
    "locations[1].count": 314,
    "locations[2].name": "china",
    "locations[2].count": 2321
}
]

我的问题是:Dimple 如何支持在这个特定 JSON 文件中编码的数据?大多数示例使用 CSV 和 TSV 文件,但不幸的是,我只能使用 JSON 文件。

【问题讨论】:

    标签: javascript json d3.js dimple.js


    【解决方案1】:

    Dimple 不能使用嵌套数据。您必须在客户端将其展平,以便为通道/位置的 每个 交叉点提供一个 JSON 对象。下面是一个如何使用 Underscore.js 的示例:

    var chartData = _.chain(data)
    .map(function(row, index){
      // for each original row, return a new row for each location
      return _.map(row.locations, function(location){
        return {
          'channel' : row.channel,
          'name' : location.name,
          'count' : location.count
        };
      });
    })
    .flatten()
    .value();
    

    (对于原始数据集中的每一行,它将返回三行,每个位置一个。这将返回一个嵌套数组的数组,因此它调用flatten 使整个数组深一层。)

    这是一个 jsBin 展示了它的实际效果:http://jsbin.com/nuvihu/edit?html,js,output

    (输出):

    如果这有帮助,这就是数据最终的样子:

    [{"channel":"politics","name":"usa","count":1454},{"channel":"politics","name":"mexico","count":3543},{"channel":"politics","name":"antarctica","count":4352},{"channel":"economics","name":"usa","count":12431},{"channel":"economics","name":"mexico","count":314},{"channel":"economics","name":"china","count":2321}]
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多