Michael TGCM Michael TGCM - 5 months ago 23
jQuery Question

Parse Nested JSON using jquery & Ajax

found a code snippet i am trying to modify but i can't seem to get it to work, This code is made to parse the json format as such

[
{
"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"
}
]


and my json format is multilevel nested such as

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


The Javascript i found is

$('#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);
});
});


So how and where would i modify this to sort through my json format?

Thanks!

Answer

The response data is an object with a property data that contains an array, which you should loop over with $.each(). Each element is an object with an artists property, and its value is an object with an Artist property (I don't know why they have this extra level of nesting, it seems redundant).

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