I am pretty new to jQuery and JSON and brand new to this site.
I am trying to display data from a JSON file using jQuery.
JSON Example:
[
{
"show":"swim",
"image": "Img1.jpg",
"brands":
[
{
"brand":"Img 1 Company",
"YAH": "Img 1 YAH"
},
{
"brand":"Img 1 Company 2",
"YAH": "Img 1 YAH 2"
}
]
},
{
"show":"swim",
"image":"Img2.jpg",
"brands": [
{
"brand":"Img 2 Company 1",
"YAH": "Img 2 YAH 1"
},
{
"brand":"Img 2 Company 2",
"YAH": "Img 2 YAH 2"
},
{
"brand":"Img 2 Company 3",
"YAH": "Img 2 YAH 3"
}
]
},
{
"show":"resort",
"image":"Img3.jpg",
"brands": [
{
"brand":"Img 3 Company 1",
"YAH": "Img 3 YAH 1"
},
{
"brand":"Img 3 Company 2",
"YAH": "Img 3 YAH 2"
}
]
}
]
I want the 'brands' array data to only show with the parent object. When I display to console.log it is correct, but when I .append it repeats all of the brands array data. It correctly displays the 'images' values and it displays all of the data from the 'brands' array, but repeats the 'brands' array data. The result displays like this:
Img1.jpg
- Img 1 Company
- Img 1 Company 2
- Img 2 Company 1
- Img 2 Company 2
- Img 2 Company 3
- Img 3 Company 1
- Img 3 Company 2
Img2.jpg
- Img 1 Company 2
- Img 2 Company 1
- Img 2 Company 2
- Img 2 Company 3
- Img 3 Company 1
- Img 3 Company 2
Img3.jpg
- Img 3 Company 1
- Img 3 Company 2
Where the result should be:
Img1.jpg
- Img 1 Company
- Img 1 Company 2
Img2.jpg
- Img 2 Company 1
- Img 2 Company 2
- Img 2 Company 3
Img3.jpg
- Img 3 Company 1
- Img 3 Company 2
I cannot figure out how to make the brands array only display the data for the parent object. this is my HTML and Script
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<meta charset="utf-8" /><body>
<div id="ImageGallery"></div>
<script>
$.getJSON('js/data.json', function(json) {
$.each(json,function(i, value){
$('#ImageGallery').append('<p>'+ value.image + '</p><ul class="brands"></ul>');
$.each(value.brands, function(index, obj){
$('ul.brands').append('<li>'+ obj.brand +'</li>');
})
});
});
</script>
</body>
Thanks!