Manitou13
Manitou13

Reputation: 35

How to fill html with local JSON data?

I'm new to javascript and the use of json. What I want to do is really simple, yet I'm struggling with it.

I need to build a website with two pages, one that show artists, the others show their works. I need to build it dynamically only with javascript and the help of a json file.

So I've already build the two pages with html and Css and let some empty space to fill it with the data. For example here is a template for the artist :

<div class="artists-id">
  <a class="frame-link"href="">
    <img id= "photo" class="photo" src=""></img>
  </a>
  <h2 id="name" class="name"></h2>
  <span class="description">
    <p id= "location" class="location"></p>
    <p id= "tagline" class="catchphrase"></p>
    <p id= "price" class="price"></p>
  </span>
  <span class="label">
    <ul class= "tags-label">
      <li class="tag-elm">
        <a href="#" id= "tag" class= "tag"></a>
      </li>
    </ul>
  </span>
</div>

I also have a JSON file (internal not external !) with all the data that look like this :

{
    "artists": [
      {
        "name": "Boris Kein",
        "id": 801,
        "city": "London",
        "country": "UK",
        "tags": ["portrait", "events", "travel", "animals"],
        "tagline": "Beauty is everywhere",
        "price": 400,
        "portrait": "BorisKein.jpg"
      },

So far I was just able to fetch the data like that :

async function fetchData() {
    const response = await fetch("javascript/data.json");
    const data = await response.json();
    console.log(data);
};
fetchData();

Now I'm little lost how can I use my data to fill the blank space in my html ?

Upvotes: 1

Views: 2440

Answers (3)

Dfranc3373
Dfranc3373

Reputation: 2177

So you will need to use Javascript in order to set the data on the page you're building and there are a vast amount of options to do so.

1. The first way is just to use plain old Javascript to take the update the page.

getElementById and innerHTML will be your best friends on this one. I recommend looking at tutorials like this one: https://www.w3schools.com/jsref/prop_html_innerhtml.asp on this.

The idea is that you define an id for a element (div, spav, table, etc.) and then add the data you want to that id.

However, using a route like this, you're most likely going to have to create some dynamic HTML in Javascript to replace in since you don't really know how many artist are coming down. ( see @Emiel Zuurbier's answer on this page where he uses template literals)

That leads to option #2

2. Use a Reactive Javascript Framework

Frameworks help do a lot of the heavy for changes on a page by allowing you to define a template and just dynamically add data for them.

There are a bunch with popular ones being React Js, Vue JS, Handlebars JS, Angular, and so much more.

This route will require you to learn about using the frameworks and installing / setting them up on your project. Most full-on reactive web projects will go for systems like these. However note that you will be having to learn how to use the framework and get it set up before you can start building with it.

Examples / info on these frameworks can be found all over:

Upvotes: 1

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20924

The easiest way to turn you values into elements is by using Template literals. Create a function which takes in a single artist object. Make that function return a template literal string with the values of the artist.

Now all you have to do is loop over each artist and create a template string per artist. Then add all those template strings to the body.

const data = {
  "artists": [{
    "name": "Boris Kein",
    "id": 801,
    "city": "London",
    "country": "UK",
    "tags": ["portrait", "events", "travel", "animals"],
    "tagline": "Beauty is everywhere",
    "price": 400,
    "portrait": "BorisKein.jpg"
  },]
};

/**
 * Create one big string with interpolated values
 */
const createArtistHTML = ({
  name,
  id,
  city,
  country,
  tags,
  tagline,
  price,
  portrait
}) => `
  <div class="artist" id="artist-${id}">
    <a class="frame-link" href="#">
      <img class="photo" src="${portrait}" alt="${name}"/>
    </a>
    <h2 class="name">${name}</h2>
    <span class="description">
      <p class="country">${country}</p>
      <p class="city">${city}</p>
      <p class="tagline">${tagline}</p>
      <p class="price">${price}</p>
    </span>
    <span class="label">
      <ul class="tags-label">
        ${tags.map(tag => `
          <li class="tag-elm">
            <a href="#" class="tag">${tag}</a>
          </li>`
        ).join('')}
      </ul>
    </span>
  </div>`;
 
// Create the HTML for each artist.
const artists = data.artists.map(createArtistHTML);

// And add it for each HTML template to the body.
artists.forEach(artist => {
  document.body.innerHTML += artist;
});

Upvotes: 4

İlker
İlker

Reputation: 2090

First of all select all the elements you want to fill in with querySelector or whichever method you want.

Let's say we select the "name" class and we will fill it with the name coming from Json data. We can do it like this;

name.innerHTML = data.artists[0].name //according to your data

Upvotes: 0

Related Questions