如何从JSON数组中检索数据?

时间:2014-03-25 12:19:04

标签: javascript json

这是我的json数据

{
"list":[{"rank":"1","fb_id":"12345","score":"3000"},
        {"rank":"2","fb_id":"12345","score":"2000"},      
        {"rank":"3","fb_id":"123456","score":"1000"},
        {"rank":"5","fb_id":"123456","score":"2500"}],
       "roundscores":[{"score1":"1000","pos1":"3","score2":"2500","pos2":"5"}]
}

从这些数据中我需要使用java脚本获取score1

我的JS

$.ajax({
type: "POST",
url: "ajaxClassifica2.jsp",
data: "selectedLevel="+selectedLevel+"&fb_id="+123456,
success: function(data) {
        alert(data);
        var jsonlist = data.list;
        var jsonround = data.roundscores;
        alert(jsonlist); 
        alert(jsonround);
        var strBuild = "";
        $.each(jsonobj, function(index, names) 
        {
                strBuild ="<ul class=\"livelli\">"
                            +" <div class=\"social\"> "
                            +"  <a href=\"#\"><img src=\"images/ico_fb.png\"></a>"
                            +"  <a href=\"#\"><img src=\"images/ico_tw.png\"></a>"
                            +" </div>"
                            +" <li><strong>Round 1:</strong> " + names.roundscores.score1 + "</li>"
                            +" <li><strong>Posizione:</strong> " + names.roundscores.pos1 + " </li>"
                            +" </ul>"
                            +" <ul class=\"livelli\">"
                            +" <div class=\"social\"> "
                            +"  <a href=\"#\"><img src=\"images/ico_fb.png\"></a>"
                            +"      <a href=\"#\"><img src=\"images/ico_tw.png\"></a>"
                            +" </div>"
                            +" <li><strong>Round 2:</strong> " + names.roundscores.score2 + "</li>"
                            +" <li><strong>Posizione:</strong> " + names.roundscores.pos2 + "</li>"
                            +" </ul>";

        });
              }
    }); 

4 个答案:

答案 0 :(得分:3)

您可以使用JSON.parse然后使用常规JavaScript命名法访问它:

var obj = JSON.parse('{"list":[...]}');
obj.roundscores[0].score1 // 1000

此外,如果您使用的是没有JSON.parse API的旧版浏览器,则可以使用JSON3等填充程序

答案 1 :(得分:2)

var json = '{ "list":[{"rank":"1","fb_id":"12345","score":"3000"},{"rank":"2","fb_id":"12345","score":"2000"},{"rank":"3","fb_id":"123456","score":"1000"},{"rank":"5","fb_id":"123456","score":"2500"}], "roundscores":[{"score1":"1000","pos1":"3","score2":"2500","pos2":"5"}] }';
var obj = JSON.parse(json);
var score1 = obj.roundscores[0].score1);

答案 2 :(得分:0)

请假设您的JSON数据位于变量&#34; rawData&#34;。

var jData = JSON.parse(rawData);
alert(jData.roundscores[0].score1);

答案 3 :(得分:0)

查看此示例可能对您有所帮助

         var jsonText = '{"name":"Frodo","address":"Hobbiton, The Shire"}';
         var person = JSON.parse(jsonText);

         alert(person.name);