一个json文件中的更多对象

我正在开发一个映射工具,我正在使用jQuery从服务器下载JSON数据。 jquery的代码目前是:

$.getJSON("start.json", function(data) { var items = []; $.each(data, function(key, val) { alert("data: " + key + "->" + val); }); }); 

json文件如下所示:

 { "type" : "obstacle", "top" : 20, "left" : 10, "height": 50, "width" : 70, "tall" : 10 } 

现在,“问题”是,正如可以清楚地看到的,在这种格式中,json只能包含一个对象。 我如何构建我的文件(以及我的jquery)以拥有多个对象?

提前致谢。

您可以使用数组来存储它们:

 { "objects": [ { "type" : "obstacle", "top" : 20, "left" : 10, "height": 50, "width" : 70, "tall" : 10 }, { "type" : "obstacle", "top" : 20, "left" : 10, "height": 50, "width" : 70, "tall" : 10 }, { "type" : "obstacle", "top" : 20, "left" : 10, "height": 50, "width" : 70, "tall" : 10 } ] } 

现在,当您迭代时,您可以访问单个对象的属性:

 $.each(data.objects, function(key, val) { console.log(key + ' => ' + val); }); 

您可以创建一个JSON对象数组,如下所示:

 [ { "type" : "obstacle", "top" : 20, "left" : 10, "height": 50, "width" : 70, "tall" : 10 } , { "type" : "obstacle", "top" : 50, "left" : 10, "height": 50, "width" : 20, "tall" : 10 } ] 

编辑:jQuery将是这样的:

 $.each(data, function(index, obstacle)) { $.each(obstacle, function(key, val) { alert("data: " + key + "->" + val); }); }