1

我将如何在 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

4 回答 4

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> 
于 2013-07-24T11:17:44.390 回答
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
}
于 2013-07-24T14:17:32.063 回答
0

首先删除()with substring();

使用nativeJSON.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);
}
于 2013-07-24T11:22:30.050 回答
0

如果你得到这个答案作为一个字符串,你必须在开始和结束时删除(和。)然后,您可以使用 jQuery 函数将字符串解析为 javascript 对象,$.parseJSON(string)并将生成的对象分配给变量,这样您就可以像往常一样访问属性。

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

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

于 2013-07-24T11:21:49.567 回答