重新格式化JSON数据

时间:2016-03-11 11:21:00

标签: javascript jquery json

问题

我有以下示例json数据,它没有格式化我需要的方式:

"stations": {
    "st1": "station 1",
    "st2": "station 2",
    "st3": "Station 3",
}

问题

如何将数据重新格式化为:

"stations": [
  {
    "id": "st1",
    "name": "station 1",
  },
  {
    "id": "st2",
    "name": "station 2",
  },
  {
    "id": "st3",
    "name": "station 3",
  }
]

试过

我尝试简单地将数据记录到首先进行测试,但我正在努力实现甚至在键/值对之间进行迭代,因为它们本质上是字符串

这是我试过的:

$.get( '/js/ajax/tube-data.json', function( data ) {

    $.each(data.stations, function () {
        // I was expecting st1, st2, st3 to show in the console
        // but got first letter of each station 
        console.log(this[0]) 
    });

}).error(function() {console.log(arguments) });

有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

Array#map()会这样做。

var object = { stations: { st1: "station 1", st2: "station 2", st3: "Station 3", } };

object.stations = Object.keys(object.stations).map(function (k) {
    return { id: k, name: object.stations[k] };
})

document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');

答案 1 :(得分:0)

我希望这会有所帮助。这是一个普通的香草代码:

var b=[];
for(key in a) {
    console.info(key);
    var x = {};
    x[key] = a[key];
    b.push(x);
}
console.info("b: ", b);