使用jquery&解析嵌套JSON;阿贾克斯

时间:2016-06-30 00:06:01

标签: javascript jquery html json ajax

发现我试图修改的代码片段,但我似乎无法让它工作,这段代码是为了解析json格式

[
  {
    "name":"Barot Bellingham",
    "shortname":"Barot_Bellingham",
    "reknown":"Royal Academy of Painting and Sculpture",
    "bio":"Barot has just finished his final year at The Royal Academy of Painting and Sculpture, where he excelled in glass etching paintings and portraiture. Hailed as one of the most diverse artists of his generation, Barot is equally as skilled with watercolors as he is with oils, and is just as well-balanced in different subject areas. Barot's collection entitled \"The Un-Collection\" will adorn the walls of Gilbert Hall, depicting his range of skills and sensibilities - all of them, uniquely Barot, yet undeniably different"
  }
]

我的json格式是多层嵌套的,例如

{
    "data": [
        {
            "artists": {
                "Artist": "Muse"
            }
        },
        {
            "artists": {
                "Artist": "Coldplay"
            }
        }
    ]
}

我找到的Javascript是

$('#search').keyup(function(){
    var searchField = $('#search').val();
    var myExp = new RegExp(searchField, 'i');
    $.getJSON('data.json', function(data){
        var output = '<ul class="searchresult">';
        $.each(data, function(key, val){
            if((val.name.search(myExp) != -1) || (val.bio.search(myExp) != -1)) {
                output +='<li>';
                output +='<h2>' + val.name + '</h2>';
                output +='<img src="images/' + val.shortname + '_tn.jpg" alt="'+ val.name +'" />';
                output +='<p>' + val.bio + '</p>';
                output +='</li>';
            }
        });
        output += '</ul>';
        $('#update').html(output);
    });
});

那么我将如何以及在何处修改此内容以对json格式进行排序?

谢谢!

1 个答案:

答案 0 :(得分:0)

响应data是一个对象,其属性data包含一个数组,您应该使用$.each()进行循环。每个元素都是一个具有artists属性的对象,它的值是一个具有Artist属性的对象(我不知道它们为什么有这种额外的嵌套级别,看起来多余)。

$.each(data.data, function(index, val) {
    var artist = val.artists.Artist;
    // do what you want with artist
});