I'm trying to get values of an object in JSON file with javascript.
My JSON file looks like this;
{
"product":"gill",
"body":
{
"name":"gill",
"thumbnail":"https://www.example.com/gill.jpg"
},
"product":"folded",
"body":
{
"name":"folded",
"thumbnail":"https://www.example.com/folded.jpg"
}
}
and my JS file looks like this:
window.onload = function(){
const apiUri ="../test.json";
const product = document.getElementById("products").children[0].id;
const data = { product : product };
fetch(apiUri, {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((json) => {
Image.setAttribute("src",json.body.thumbnail)
})
.catch((err) => console.log(err));
console.log(data);
}
when page loads, the Image src gets always the last product in json file, which is folded.
I want to search for a product which has been get by element id, and set the image src of that product in JSON file.