javascript - 将 Excel 文件转换为 JSON : design of JSON code check

标签 javascript sql json excel d3.js

我想将数据从 Excel 文件转换为 JSON 文件。但是,我不确定 JSON 代码的设计(即它是否以正确的方式组织以便轻松处理?) 我将将此 JSON 文件与 D3.js 一起使用。

这是我的 Excel 文件的一小部分:

enter image description here

我想将此数据转换为 JSON 文件,以便将其与 D3.js 一起使用。这是我到目前为止所拥有的:

enter image description here

所以我的问题是:这是组织数据以便与 D3.js 一起使用的良好设计(方式)吗? 这是示例输出:

enter image description here

提前致谢!

最佳答案

这是一个有点主观的问题,但根据我的经验,有更好的方法:

由于您在 d3 中工作,因此您可能会执行以下操作:

d3.selectAll('div')
  .data(entities)
.enter()
  .append('div')
  ...

所以你希望entities是一个数组。问题是你的实体是什么?有没有一种观点认为实体是世界上所有国家?有没有一种观点认为实体是所有国家+所有地区+全世界?或者,所有 View 都只是选定区域中的所有国家/地区,不包括该区域本身吗?

除非您建议的 JSON 结构与您计划显示的实体组合相匹配,否则您的代码将必须对数组进行一系列连接和/或过滤,以获得单个实体数组你可以绑定(bind)到。也许这没问题,但它会在代码和数据结构之间产生一些不必要的耦合。

根据我的经验,事实证明,最灵活的方法(也可能是编码方面最简单的方法)是保持层次结构平坦,就像在 Excel 文件中一样。因此,不必将区域编码到层次结构中,只需将它们放在一个平面数组中,如下所示:

{
  "immigration": [
    {
      "name": "All Countries"
      "values: [
        { "Year": ..., "value": ... },
        { "Year": ..., "value": ... },
        ...
      ]
    },
    {
      "name": "Africa"
      "values: [
        { "Year": ..., "value": ... },
        { "Year": ..., "value": ... },
        ...
      ]
    },
    {
      "name": "Eastern Africa"
      "continent": "Africa"
      "values": [
        { "Year": ..., "value": ... },
        { "Year": ..., "value": ... },
        ...
      ]
    },
    {
      "name": "Burundi"
      "continent": "Africa"
      "region": "East Africa"
      "values": [
        { "Year": ..., "value": ... },
        { "Year": ..., "value": ... },
        ...
      ]
    },
    {
      "name": "Djibouti"
      "continent": "Africa"
      "region": "East Africa"
      "values": [
        { "Year": ..., "value": ... },
        { "Year": ..., "value": ... },
        ...
      ]
    },
    ...
  ]
}

请注意,即使数组是扁平的,这里仍然存在层次结构 - regionsub-region 属性。

您必须进行一些过滤才能仅提取您想要显示的国家/地区。但这比遍历您建议的层次结构更简单:

var africanEntities = data.immigration.filter(function(country) {
  return country.continent == "Africa";
}); // Includes the region "East Africa"

var justCountries = data.immigration.filter(function(country) {
  return country.continent != null && country.region != null;
});

此外,d3 有很棒的 d3.nest() ,它可以让您轻松地将这种平面数据转变为分层数据:

var countriesByContinent = d3.nest()
  .key(function(d) { return d.continent; })
  .map(data.immigration);

var africanEntities = countriesByContinent['Africa'];

希望有帮助......

关于javascript - 将 Excel 文件转换为 JSON : design of JSON code check,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26538312/

相关文章:

javascript - Angularjs 使用 ng-repeat 隔离范围指令

SQL 在分隔符上拆分字符串并设置为新列

python - 动态 SQL WHERE 子句生成

更改列格式的 SQL 函数

javascript - 在 Node.js 中迭代大量 JSON 文件

c# - Newtonsoft.Json 使用 php 7.0 json_encode 数组字符串反序列化问题

javascript - 无符号右移函数不适用于负输入

javascript - 在 Android 的调整大小或方向更改事件后获取正确的窗口宽度

javascript - 为什么在JavaScript中032 * 2 = 52?

json - 将 JSON 从 Express 发送到外部服务器