So I’m trying to parse some nested json and the way I’m trying to access it is confusing me on how I can add it back to its own individual ‘item’. Each item contains an image, a caption, and possibly tags. The image source and caption are nested on the same level together so they can be accessed within the same each function, however the tags object (which is also on the same level as the image source and caption) includes an array, that needs to be accessed using a second each function to get each tag. I’m able to parse each tag using the following code, but I’m not sure how I can pass the tags object data back to the initial each function. Any help would be greatly appreciated!
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 used to access JSON data
$(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
});
}
});
});
Concatenate all the names and then append them to the container.