我有一個對象數組,每個對象都包含一個不確定長度的位置和鏈接數組。我如何創建一個帶有循環的多級JSON對象?生成多級JSON
最終JSON應該像
item1: [
{ "location": [
{"latitude": value, "longitude": value, "stopNum": value, "fileName": value }
],
"links": [
{"latitude": value, "longitude": value, "stopNum": value, "fileName": value },
{"latitude": value, "longitude": value, "stopNum": value, "fileName": value },
{"latitude": value, "longitude": value, "stopNum": value, "fileName": value }
]
}
],
item2: [ //repeat of above ]
我遇到的問題是如何正確地形成的對象。該數組包含的對象定義爲
function Links(){
this.location = null;
this.links= [];
function getLocation(){
return location;
}
function setLocation(marker){
this.location = marker;
}
function getLinks(){
return links;
}
}
我目前的解決方案是
var json=[];
var linkData;
for (var i=0; i < tourList.length; i++){
var data = tourList[i];
//create new child array for insertion
var child=[];
//push location marker data
child.push({
latitude: data.location.position.$a,
longitude: data.location.position.ab,
stopNum: i,
filename: data.location.title
});
//add associated link data
for (var j=0; j<data.links.length; j++){
linkData = data.links[i];
child.push({
latitude: linkData.position.$a,
longitude: linkData.position.ab,
stopNum: i+j,
fileName: linkData.title
});
}
//push to json array
json.push(child);
}
//stringify the JSON and post results
var results= JSON.stringify(json);
然而,這並不完全工作,因爲
$post= json_decode($_POST['json'])
PHP語句返回一個畸形的陣列其中$post.length
被視爲未定義的常量。我假設這是由於格式不正確。
使用上面定義的對象,如何創建一個格式良好的JSON發送到服務器?
的stringify()
當前結果是
[
{"latitude":43.682211,"longitude":-70.45070499999997,"stopNum":0,"filename":"../panos/photos/1-prefix_blended_fused.jpg"},
[
{"latitude":43.6822,"longitude":-70.45076899999998,"stopNum":0,"fileName":"../panos/photos/2-prefix_blended_fused.jpg"}
],
{"latitude":43.6822,"longitude":-70.45076899999998,"stopNum":1,"filename":"../panos/photos/2-prefix_blended_fused.jpg"},
[
{"latitude":43.68218,"longitude":-70.45088699999997,"stopNum":1,"fileName":"../panos/photos/4-prefix_blended_fused.jpg"},
{"latitude":43.68218,"longitude":-70.45088699999997,"stopNum":2,"fileName":"../panos/photos/4-prefix_blended_fused.jpg"}
]
]
而且,我使用$post.length
在
$post = json_decode($POST['json']);
for ($i=0; $i<$post.length; $i++) { }
來迭代所處理的陣列之上。
POST請求是通過定義爲
$.ajax({
type: "POST",
url: "../includes/phpscripts.php?action=postTour",
data: {"json":results},
beforeSend: function(x){
if (x && x.overrideMimeType){
x.overrideMimeType("application/json;charset=UTF-8");
}
},
success: function(data){
if (data == "success")
console.log("Tour update successful");
else
console.log("Tour update failed");
}
});
您是不是指'count($ post)'而不是'$ post.length'? –
你可以發佈你從那個JavaScript獲得的示例JSON輸出嗎?另外,你如何發佈這個PHP腳本? – Andre
另外,我相信你想檢查'strlen($ post);'而不是'count();'。 – Andre