0

我怀疑我使用了错误的术语,所以请多多包涵。

我一直在非常有效地使用 mustache.js 来处理 API 的 JSON 输出。我正在使用一个外观看起来非常相似的兄弟 API,只是没有顶级名称。我正在尝试弄清楚如何将新的 JSON 输出调整为其他格式,以便我可以继续使用我的 mustache.js 方法(这似乎是更容易的选项,另一个使用的是 mustache.js 以外的东西,我试图避免)。

我可以使用 mustache.js 使用顶级名称“记录”非常轻松地迭代以下 JSON 主体:

{"records":
[{"dt_created":"08/23/2013 04:49:13 PM","created_by":"x,   x","dt_updated":"08/23/2013 04:49:13 PM","updated_by":"x, x","field_60374":  ["Project 67"],"field_60331":["Ability to adjust the number of lines dynamically based on   the mood of the person 3 rows down, 4th cube, 11th building. A breakthrough in mind-control   data processing."],"field_60333":   [{"id":"x","first":"x","last":"x"}],"field_60394":  [{"id":"x","first":"x","last":"x"}],"field_60414":["11"],"field_60375":  ["22"],"field_60395":["A"],"record_id":"1920704","form_id":"10898"},
{"dt_created":"08/23/2013 04:47:45 PM","created_by":"x, x","dt_updated":"08/23/2013 04:47:45 PM","updated_by":"x, x","field_60374":["Project 2"],"field_60331":["Very cool project to allow more than a single invoice to be in an ERP at any one time. Quite a big leap forward."],"field_60333": [{"id":"x","first":"x","last":"x"}],"field_60394": [{"id":"x","first":"x","last":"x"}],"field_60414":["x,  x"],"field_60375":["60"],"field_60395": ["A"],"record_id":"1920703","form_id":"10898"}],
"meta":{"total":2,"count":2}
}

由于缺少顶级名称,我无法遍历的格式是:

[{"id":"x","user": {"id":"x","first_name":"x","last_name":"x"},"title":"Test Post 3","text":"This is an equally cool and enthralling post.","created_at":"2013-08-29T17:46:04.801Z","updated_at":"2013-08-29T17:46:04.804Z","num_comments":0,"num_likes":0},
{"id":"y","user":   {"id":"212342277","first_name":"x","last_name":"x"},"title":"Test Post 1","text":"Super cool content you want to read!","created_at":"2013-08- 29T17:44:58.188Z","updated_at":"2013-08-29T17:44:58.190Z","num_comments":0,"num_likes":0}]

我尝试了以下方法将第二个 JSON 示例转换为第一个格式:

$.ajax({
     […….],
     success: function(json_data){
                        alert("success");
                             var template=$('#listPosts').html();
                        var stuff = {"records":json_data}; //here
                        var stuff = JSON.stringify(stuff); //here
                        alert(stuff);
                           //var html = Mustache.to_html(template, json_data);
                        var html = Mustache.to_html(template, stuff);
                        //$('.content-pane').empty();                                                                                                                               
                        $('#listOfPostsContainer').html(html); 
}
}

我有一个弹出警告,其中包含 var 'stuff' 中的内容,它的格式似乎与第一个 JSON 示例一样,但 mustache.js 不解析它(我已验证 mustache.js 执行)。在尝试解决任何其他问题之前,我想了解如何在上述 AJAX 调用成功属性中向 JSON 数组添加顶级名称是否正确,或者我是否必须以不同的方式进行操作。

如果我遗漏了一些东西来帮助解释这一点,请告诉我,这样我就可以添加它。

4

0 回答 0