En supposant que les données JSON est correctement structuré:
let jsonData = [
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"}
];
Vous pouvez le faire en quelques différentes façons, dans le code suivant, nous créons d'abord un récipient div
puis boucle sur le tableau JSON créer un nouvel élément image, puis l'ajouter au conteneur. Enfin, cette div est ajouté l'élément du corps:
let jsonData = [
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"}
];
const container = document.createElement('div');
const bodyElement = document.querySelector('body');
const images = jsonData.map(image => {
let imageEl = document.createElement('img');
imageEl.setAttribute('src', image.src);
imageEl.setAttribute('height', image.height);
imageEl.setAttribute('width', image.width);
return imageEl;
});
for (let image of images) {
container.appendChild(image);
}
bodyElement.appendChild(container);
https://jsbin.com/qokilubeze/edit?html,js,output
Ceci peut être encore simplifiée:
const container = document.createElement('div');
const bodyElement = document.querySelector('body');
for (let i = 0; i < jsonData.length; i++) {
let imageEl = document.createElement('img');
imageEl.setAttribute('src', jsonData[i].src);
imageEl.setAttribute('height', jsonData[i].height);
imageEl.setAttribute('width', jsonData[i].width);
container.appendChild(imageEl);
}
bodyElement.appendChild(container);
Ou:
const container = document.createElement('div');
const bodyElement = document.querySelector('body');
jsonData.map(image => {
let imageEl = document.createElement('img');
imageEl.setAttribute('src', image.src);
imageEl.setAttribute('height', image.height);
imageEl.setAttribute('width', image.width);
container.appendChild(imageEl);
});
bodyElement.appendChild(container);
Ce n'est pas un JSON valide. Si vous avez une dictée de dicts, alors il vous manque les accolades et les virgules. –