转换为适当的格式

时间:2014-04-28 14:26:55

标签: arrays format json

如何将以下json转换为所需格式?

我有什么:

{
  "1":{
    "name":"Room1",
    "agegroup":"38 to 67",
    "display_agegroup":"Months",
    "0":"After School Care"
  },
  "5":{
     "name":"new room",
     "agegroup":"3.08 to 4.",
     "display_agegroup":"Years",
     "0":"After School Care",
     "1":"Before School Care"
  }
}

我需要什么:

[{
   "id":"1",
   "field1":"Room1",
   "field2":"38 to 67",
   "field3":"Months",
   "field4":"After School Care"},
 {
   "id":"5",
   "field1":"new room",
   "field2":"3.08 to 4.",
   "field3":"Years",
   "field4":"After School Care & Before School Care"
}]

请指导我。

1 个答案:

答案 0 :(得分:0)

var out = [];
var input = {
  "1": { /* ... */ },
  "5": { /* ... */ }
};

_.each(_.keys(input), function(el) {
  var obj = {
    "id": el
  };

  _.each(_.keys(input[el], function(k, idx) {
    obj["field"+(1+idx)] = input[el][k];
  });

  out.push(obj);
});

为方便起见,使用Underscore.js。如果您不能/不胜,那么用标准JS代码替换_.keys_.each非常简单。