2016-06-30 24 views
-2

發現一段代碼我試圖修改,但我似乎無法得到它的工作,這個代碼是由解析JSON格式等解析嵌套的JSON使用jQuery和Ajax的

[ 
    { 
    "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格式進行排序?

謝謝!

回答

0

響應data是一個對象,其屬性爲data,它包含一個數組,您應該使用$.each()進行循環。每個元素都是一個具有artists屬性的對象,它的值是一個具有Artist屬性的對象(我不知道爲什麼它們具有這種額外級別的嵌套,它似乎是多餘的)。

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

>>(我不知道爲什麼他們有嵌套的這種額外的水平,這似乎是多餘的) 它只是樣品反黑組,的theres要去更多信息,例如相冊,總的軌道等 –