Consume a JSON with Javascript!

Asked

Viewed 994 times

-1

I have a JSON with the following data of some products:

  • Name
  • Photo
  • Price

And I have some HTML cards that I would like them to present themselves there; how could I consume this JSON to show it inside these cards.

NOTE: Cards are only spaces to enter the image, price and product name.

1 answer

1


Place an ID on each of the HTML elements that will receive the information, for example using a Bootstrap 4 card:

<div class="card shadow" style="width: 18rem;">
    <img id="avatar" class="card-img-top" src="#" alt="Image">
    <div class="card-body">
        <h5 id="first_name" class="card-title"></h5>
        <p id="last_name" class="card-text"></p>
    </div>
</div>

Use the fetch of Javascript passing the URL of your API, in this example to put the data and the image of a user on the previous card we do:

const url = 'https://reqres.in/api/users/2'; // Troque pela URL da sua API

function readJson() {
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error("Erro HTTP: " + response.status);
            }
            return response.json();
        })
        .then(json => {
            this.response = json;
            document.getElementById('avatar').src = response.data.avatar;
            document.getElementById('first_name').innerHTML = response.data.first_name;
            document.getElementById('last_name').innerHTML = response.data.last_name;
        })
        .catch(function () {
            this.dataError = true;
        })
}

readJson();

Follows the link of this example in operation.

  • This will work, but I have a local JSON as I could find it through the const url = '.. /Assets/products.json' would be this way?

  • You should install a web server locally and use localhost with your URL.

  • I was able to host it on a https://thaleshenrique38.000webhostapp.com/products.json. but even putting the URL and ID’s the same as the application ends up not being able to consume!

  • As you have several items, try building a loop to catch them one by one. To get the image, in your case it changes a little because of the array that your API returns, then it would look something like Response.data.images[0]. imageurl.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.