我有一个json文件,该文件的数据格式如下:
{
"rigidBodies": [
{
"name": "ball1.png", "imagePath": "ball1.png", "origin": {"x": 0, "y": 0},
"polygons": [
[
{"x": 0.16999998688697815, "y": 0.5724999904632568},
{"x": 0.16749995946884155, "y": 0.5324999690055847},
{"x": 0.16999998688697815, "y": 0.45250001549720764}
],
[
{"x": 0.16999998688697815, "y": 0.45250001549720764},
{"x": 0.16749995946884155, "y": 0.375},
{"x": 0.2199999988079071, "y": 0.3725000023841858}
]
]
}
]
}
我想在数组中推送数据,所以我尝试过这种方式,并说错误,
var poly = new Array();
// note : parsing json
$.getJSON('my_assets/addPhysics/testPhysics.json', function(data) {
//do stuff with your data here
$.each(data, function(i, item) {
// for(var i=0;i<item[0].length;i++){
poly.push(item[0][i].x,item[0][i].y);
//}
});
});
答案 0 :(得分:1)
data
是一个对象,您要循环的数组位于polygons
数组内的rigidBodies
属性中。你需要这样做:
var data = {
"rigidBodies": [{
"name": "ball1.png",
"imagePath": "ball1.png",
"origin": {
"x": 0,
"y": 0
},
"polygons": [
[{
"x": 0.16999998688697815,
"y": 0.5724999904632568
}, {
"x": 0.16749995946884155,
"y": 0.5324999690055847
}, {
"x": 0.16999998688697815,
"y": 0.45250001549720764
}],
[{
"x": 0.16999998688697815,
"y": 0.45250001549720764
}, {
"x": 0.16749995946884155,
"y": 0.375
}, {
"x": 0.2199999988079071,
"y": 0.3725000023841858
}]
]
}]
}
var poly = [];
$.each(data.rigidBodies, function(i, body) {
$.each(body.polygons, function(j, polygon) {
$.each(polygon, function(k, coords) {
poly.push([coords.x, coords.y]);
});
});
});
document.getElementById("output").innerHTML = JSON.stringify(poly);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
答案 1 :(得分:0)
你应该试试这个
poly.push([item[0][i].x,item[0][i].y]);
所以poly [0] [0]是X
和poly [0] [1]是Y