我将如何读取Web服务的以下json响应?

时间:2013-07-24 11:15:00

标签: javascript jquery json jsonp

我将如何在java脚本中阅读以下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
    }
}

]);

4 个答案:

答案 0 :(得分: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> 

答案 1 :(得分:0)

如果您将此答案作为字符串获得,则必须在开头和结尾处删除()。然后,您可以使用jQuery-function $.parseJSON(string)将字符串解析为javascript-object,并将结果对象分配给变量,这样您就可以像往常一样访问属性。

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

要使用object[0].submission.title访问第一次提交的标题,并使用object[i].submission.title访问第i次提交的标题。

答案 2 :(得分: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);
}

答案 3 :(得分: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
}