将API中的JSON数据转换为有用的格式?

时间:2014-11-01 15:53:00

标签: javascript json

我有一个以这种格式返回指标数据的API:

[
    {
            "concept": "population",
            "year": 2012,
            "value": 9.5,
            "country-name": "Sweden",
    },
    {
            "concept": "education",
            "year": 2012,
            "value": 12,
            "country-name": "Sweden",
    },
    {
            "concept": "population",
            "year": 2012,
            "value": 5,
            "country-name": "Norway",
    },
    {
            "concept": "eduction",
            "year": 2012,
            "value": 12,
            "country-name": "Norway",
    }
]

基于此,我通常需要按国家和年份对此进行分组,以获得类似:

var data = [
   {id : Sweden, population : 9.5, education: 12},
   {id : Norway, population : 5, education: 12},
]

或者只是按国家/地区和年份值作为数组:

var data = [
   {id : Sweden, values : [ { year : 2012, population : 9.5, education: 12 }, {...} ]},
   {id : Norway, values : [ { year : 2012, population : 5, education: 12 }, {...} ]},
]
  1. 哪些JS库可以帮助管理这些常见的数据转换?
  2. 您能提供一个上述例子(使用库或vanilla js)吗?

3 个答案:

答案 0 :(得分:2)

你可以自己做,只需迭代并创建你需要的东西,比如

var data = [];

json.forEach(function(item) {
    var country = item['country-name'],
        match   = false,
        obj     = {}

    data.forEach(function(dataItem, i) {
        if (dataItem.id === country) {
            match = true;
            obj   = data[i];
        }
    });

    obj.id = country;
    obj[item.concept] = item.value;

    if (!match) data.push(obj)
});

FIDDLE

答案 1 :(得分:0)

您可能会发现一个对象比数组更容易使用:

var data = {};
indicatordata.forEach(function(item){
    var country = item['country-name'];
    var year = item.year;
    data[country] = data[country] || {id: item['country-name'], values: {}};
    var values = data[country].values;
    values[year] = values[year] || {};
    values[year][item.concept] = item.value;
});

答案 2 :(得分:-1)

您可以使用D3执行此操作。 d3.nestArray.prototype.reduce具体而言。代码是声明性的,易于维护。



var rawData = [
  {
    "concept": "population",
    "year": 2012,
    "value": 9.5,
    "country-name": "Sweden",
  },
  {
    "concept": "education",
    "year": 2012,
    "value": 12,
    "country-name": "Sweden",
  },
  {
    "concept": "population",
    "year": 2012,
    "value": 5,
    "country-name": "Norway",
  },
  {
    "concept": "eduction",
    "year": 2012,
    "value": 12,
    "country-name": "Norway",
  }
];

var data = d3.nest()
  .key(function(d)
  {
    return d['year'];
  })
  .key(function(d)
  {
    return d['country-name'];
  })
  .rollup(function(group)
  {
    return group.reduce(function(result, d)
    {
      result[d['concept']] = d['value'];
      return result;
    }, {});
  })
  .entries(rawData);

console.log(data);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
&#13;
&#13;