2013-07-24 81 views
1

我將如何讀取java腳本中的以下json響應?我將如何閱讀web服務的followong json響應?

這是一個由JavaScript處理的Web服務響應,但我無法讓它如何讀取每個提交標題和開始日期。 任何幫助欣賞能力。

([ 
{ 
    "submission": { 
     "title": "Attended band concert", 
     "full": "met with homeroom teacher after concert, very nice, Joker Jr. is   doing well", 
     "start_date": "2013-06-18", 
     "end_date": null 
    } 
}, 
{ 
    "submission": { 
     "title": "she's complaining about", 
     "full": "something", 
     "start_date": "2013-06-20", 
     "end_date": null 
    } 
} 

]);

+2

這不是JSON。它有'('和')'。 – Quentin

回答

0

請對這個例子看,

JSON

{ 
"news1": "This is a first sample news feed", 
"news2": "This is a second sample news feed", 
"news3": "This is a third sample news feed" 
} 

HTML

<ul> 
    <li><div id="news1" style="height:100px;width:auto"></div> </li> 
    <li><div id="news2" style="height:100px;width:auto"></div></li> 
    <li><div id="news3" style="height:100px;width:auto"></div> </li> 
</ul> 

jQuery的

<script type="text/javascript"> 
$(document).ready(
    function() { 
     $.getJSON('script/news1.js', function(jd) { 
    $('#news1').append('<p>' + jd.news1 + '</p>'); 
    $('#news2').append('<p>' + jd.news2 + '</p>'); 
    $('#news3').append('<p>' + jd.news3 + '</p>'); 
    }); 
}); 
</script> 
+0

亞,但這裏OP似乎使用json對象的數組。 for循環似乎是需要的 –

0

如果你得到這個答案,你有一個字符串刪除()在開始和結束。然後,您可以使用jQuery函數$.parseJSON(string)將字符串解析爲javascript對象,並將生成的對象分配給變量,以便像往常一樣訪問屬性。

var object = $.parseJSON(response.substring(1, response.length-2)); 

要訪問的第一次提交的標題中使用object[0].submission.title和訪問第i個提交使用object[i].submission.title的稱號。

0

先用substring()刪除();

使用本地JSON.parse()函數來獲取JSON對象

然後通過陣列循環。

var x=xhr.response, 
y=x.substring(1,x.length-2),//or -3 
o=JSON.parse(y); 
for(var a=0;a<o.length;a++){ 
var s=o[a].submission; 
console.log(s.title,s.full,s.start_date,s.end_date); 
} 

較短方式

var x=xhr.response; 
for(var a=0,b;b=JSON.parse(x.substring(1,x.length-2))[a];++a){ 
console.log(b.title,b.full,b.start_date,b.end_date); 
} 

最快的方式(反向)

var x=JSON.parse(xhr.response.substring(1,xhr.response.length-2)),l=x.length; 
while(l--){ 
var a=x[l].submission; 
// even if it's reversed l can be used as index for your elements 
console.log(a.title,a.full,a.start_date,a.end_date); 
} 
0
var data=[ 
{ 
    "submission": { 
     "title": "Attended band concert", 
     "full": "met with homeroom teacher after concert, very nice, Joker Jr. is   doing well", 
     "start_date": "2013-06-18", 
     "end_date": null 
    } 
}, 
{ 
    "submission": { 
     "title": "she's complaining about", 
     "full": "something", 
     "start_date": "2013-06-20", 
     "end_date": null 
    } 
}] 

    `alert(data[0].submission.title)`//it gives the title 
     alert(data[0].submission.start_date)//gives date 

你也可以將for循環讀取所有的屬性。

for(var i=0;i<=data.length;i++){ 
     alert(data[i].submission.title)//gives title 
     alert(data[i].submission.start_date)//gives date 
}