【问题标题】:Reformat JSON data [duplicate]重新格式化 JSON 数据 [重复]
【发布时间】:2016-03-11 11:21:00
【问题描述】:

问题

我有以下未格式化的示例 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) });

有没有更好的方法来做到这一点?

【问题讨论】:

标签: javascript jquery json


【解决方案1】:

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>');

【讨论】:

  • 正是我的意思,谢谢
【解决方案2】:

我希望这会有所帮助。它是一个普通的代码来做同样的事情:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多