在Angular Js中解析非标准JSON

时间:2016-09-12 18:26:24

标签: javascript angularjs json

我以下列格式从Restful服务获得JSON响应,

{
   "comments":{
      "columns":[
         "clientId",
         "treatmentDate",
         "comments",
         "photo",
         "practitioner"
      ],
      "records":[
         [
            "1",
            "2016-09-12",
            "Some Coments",
            "0",
            "Doc 4"
         ],
         [
            "1",
            "2016-09-11",
            "DDD oNE",
            "1",
            "Docc 3"
         ]
      ]
   }
}

记录以表名开头,后面是单独的列和记录数组。 Angular不接受这种格式的数据。但是,如果我提供如下标准格式的数据,它就可以完美地运行。

[
   {
      "clientId":"1",
      "treatmentDate":"2016-09-12",
      "comments":"Some Coments",
      "photo":"0",
      "practitioner":"Doc 4"
   },
   {
      "clientId":"1",
      "treatmentDate":"2016-09-11",
      "comments":"DDD oNE",
      "photo":"1",
      "practitioner":"Docc 3"
   }
]

是否有指令可以为我做这个或者我应该创建一个自定义函数,任何想法?

1 个答案:

答案 0 :(得分:0)

是否有理由不能手动重塑数据以符合您期望的格式?

var data = json.comments.records.map(function(record) {
    return json.comments.columns.reduce(function(reshaped, columnName, idx) {
        reshaped[columnName] = record[idx];
        return reshaped;
    }, {});
});

虽然要小心;这要求records中每个数组的长度始终与列名的数量相同。