-1

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.

gmg
  • 1
  • 2

1 Answers1

0

See the JSON specification:

The names within an object SHOULD be unique.

and

When the names within an object are not unique, the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only. Other implementations report an error or fail to parse the object, and some implementations report all of the name/value pairs, including duplicates.

Change the design of your JSON.

If you want to have multiple products, use an array of products.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335