2012-04-07 42 views
0

所以我试图解析一些嵌套的JSON,并且我试图访问它的方式让我很困惑,我怎么才能将它添加回它自己的单个'item'中。每个项目都包含图像,标题和可能的标签。图像源和标题一起嵌套在同一级别,因此可以在同一个函数内访问它们,但标签对象(与图像源和标题位于同一级别)包含一个数组,它需要是使用第二个函数访问每个标签。我能够使用下面的代码解析每个标签,但我不确定如何将标签对象数据传递回最初的每个函数。任何帮助将不胜感激!如何从每个函数内的每个函数中分析嵌套JSON中的数据?

JSON Structure: 

{ 
"data": [ 
    { 
    "source": "http://example.com/picture1.jpg", 
    "caption": "First caption", 
    "tags": { 
     "data": [ 
      { 

       "name": "Cats One" 
      }, 
      { 
       "name": "Dogs One" 
      } 
     ] 
    } 
    } 
    { 
    "source": "http://example.com/picture2.jpg", 
    "caption": "Second caption", 
    "tags": { 
     "data": [ 
      { 

       "name": "Cats Two" 
      }, 
      { 
       "name": "Dogs Two" 
      } 
     ] 
    } 
    } 
] 
} 

的jQuery用来访问JSON数据

$(document).ready(function(){ 

    var url = "http://example.com"; 

    $.getJSON(url, function(json) { 
     $('#wrapper').prepend('<div id="container"></div>'); 
     $.each(json.data, function(i, data) { 
      //Adds each entry to container 
      $("#container").append('<ul class="image">' + '<li class="source"><img src="' + data.source + '" /></li>' + '<li class="caption">' + data.caption + '</li>' + '</ul>'); 
      //Checks if tags exist for each element 
      if (typeof(this.tags) === 'object') { 
       $.each(this.tags.data, function() { 
        //console.log(this.name); 
           //not sure what to add here to append these tags in a li tag above 
       }); 
      } 

    }); 
}); 

回答

1

串连所有的名字,然后将它们添加到容器中。

... 
var names = ""; 
$.each(this.tags.data, function(idx) { 
    if(idx > 0) names += ","; 
    names += this.name; 
}); 
$("#container").append($("<li></li>").append(names)); 
... 
+0

不得不修改一下,以得到我想要的结构,但工作完美!谢谢! – mkp 2012-04-07 16:16:36