Answer the question
In order to leave comments, you need to log in
How to properly extract data from JSON file?
Created json file:
{
"test" : {
"x" : "23",
"y" : "23",
"img" : [
{"name" : "01"},
{"name" : "02"},
{"name" : "03"}]
},
"test2" : {
"x" : "23",
"y" : "23",
"img" : [
{"name" : "01"},
{"name" : "02"},
{"name" : "03"}]
},
"test3" : {
"x" : "23",
"y" : "23",
"img" : [
{"name" : "01"},
{"name" : "02"},
{"name" : "03"}]
},
"test4" : {
"x" : "23",
"y" : "23",
"img" : [
{"name" : "01"},
{"name" : "02"},
{"name" : "03"}]
}
}
$.getJSON("../js/districts.json", function(data) {
for (var i in data) {
var row = data[i];
var district = i;
var img = row.img;
$('.districts').append("<div id='" + district + "'></div>");
$("#" + district).append("<div class='popup'></div>");
for (var i in img) {
$('.popup').append("<img src=\"/img/" + district + "/" + img[i].name + ".png\">");
}
}
});
<div class="districts">
<div id="test">
<div class="popup">
<img src="/img/test/01.png">
</div>
<div class="popup">
<img src="/img/test/02.png">
</div>
<div class="popup">
<img src="/img/test/03.png">
</div>
</div>
<div id="test2">
<div class="popup">
<img src="/img/test2/01.png">
</div>
<div class="popup">
<img src="/img/test2/02.png">
</div>
...
<div class="districts">
<div id="test">
<div class="popup">
<img src="/img/test/01.png">
<img src="/img/test/02.png">
<img src="/img/test/03.png">
<img src="/img/test2/01.png">
<img src="/img/test2/02.png">
...
Answer the question
In order to leave comments, you need to log in
var root = $('<div class="districts" />'),
box, child;
for (var k in data) {
if (data.hasOwnProperty(k)) {
box = $('<div class="popup" />');
child = $('<div calss="' + k + '" />').appendTo(box);
for (var i in data[k].img) {
if (data[k].img.hasOwnProperty(i)) {
$('<img src="/img/' + k + '/' + data[k].img[i].name + '.png" />').appendTo(child);
}
}
box.appendTo(root);
}
}
$('body').append(root); // выводим на экран
// (!) при этом, выводим один раз, а не мучаем DOM на каждой итерации
<div class="districts">
<div class="popup">
<div calss="test">
<img src="/img/test/01.png">
<img src="/img/test/02.png">
<img src="/img/test/03.png">
</div>
</div>
<div class="popup">
<div calss="test2">
<img src="/img/test2/01.png">
<img src="/img/test2/02.png">
<img src="/img/test2/03.png">
</div>
</div>
<div class="popup">
<div calss="test3">
<img src="/img/test3/01.png">
<img src="/img/test3/02.png">
<img src="/img/test3/03.png">
</div>
</div>
<div class="popup">
<div calss="test4">
<img src="/img/test4/01.png">
<img src="/img/test4/02.png">
<img src="/img/test4/03.png">
</div>
</div>
</div>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question