skip to Main Content

I’m currently having trouble in regards to pulling stuff from a JSON file into my HTML page. So to start, I currently have this code in a JSON file, which is all the items I have (so far) that I want to use for a project to create an online store.

(EDIT: Needed to make this correct as this was originally a Javascript file.)

[
    {
        "id": 1,
        "productName": "Chutes and Ladders",
        "image": "../public/ChutesandLadders.jpg",
        "price": 15.75,
        "salePrice": 15.75
    },
    {
        "id": 2,
        "productName": "Monopoly",
        "image": "../public/Monopoly.jpg",
        "price": 15.25,
        "salePrice": 15.25
    },
    {
        "id": 3,
        "productName": "Clue",
        "image": "../public/Clue.jpg",
        "price": 20.00,
        "salePrice": 15.20
    },
    {
        "id": 4,
        "productName": "The Game of Life",
        "image": "../public/GameofLife.jpg",
        "price": 16.00,
        "salePrice": 10.00
    },
    {
        "id": 5,
        "productName": "TRESomme Shampoo",
        "image": "../public/Tresomme.jpg",
        "price": 45.00,
        "salePrice": 30.00
    },
    {
        "id": 6,
        "productName": "Michael Kors Purse",
        "image": "../public/MichaelKorsPurse.jpg",
        "price": 145.00,
        "salePrice": 145.00
    },
    {
        "id": 7,
        "productName": "Apple Watch Ultra",
        "image": "../public/AppleWatch.jpg",
        "price": 200.00,
        "salePrice": 175.00
    }
]

Then to show a sample of it, I have this information on my HTML page (index.html) where I want to change the data to the data I have from the JSON file.

<div class="badge bg-dark text-white position-absolute" style="top: 0.5rem; right: 0.5rem">Sale</div>  
  <img class="card-img-top" width="450" height="200" src="Clue.jpg" alt="..." />         
     <div class="card-body p-4">
        <div class="text-center">
           <h5 class="fw-bolder">Clue</h5>
              <div class="d-flex justify-content-center small text-warning mb-2">
                 <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                 </div>
              <span class="text-muted text-decoration-line-through">$20.00</span>
              $15.20
           </div>
        </div>
        <div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
           <div class="text-center"><a class="btn btn-outline-dark mt-auto" href="#">Add to cart</a></div>
        </div>
     </div>
  </div>

Is there a way to import JSON data into an HTML file, where I can actually do this?

2

Answers


  1. One of the ways to do this is using the fetch() API.
    Just add a script tag in your body

    <script>
       fetch('data.json')
         .then(function(res){
             return res.json()
         })
         .then(function(data){
              return appendData(data)
          })
        function appendData(data){
            var con=document.getElementById("main-container")
            for(let i=0;i<data.length;i++){
                var d=document.createElement("div")
                d.textContent="Name: "+data[i].productName
                //add the data in whatever html element you want and then append it to the container
                con.appendChild(d);
            }
         }
    </script>
    

    I hope this helps

    Login or Signup to reply.
  2. Here are the steps you might take.

    1. Make sure your JSON is imported/fetched etc, and parsed.

    2. Either:

      a) find the object using the value of its productName property, create some HTML for that one object, and append it to the page, or

      b) map over the array and for each object create some HTML. map returns an array so you would join it up, and then append that HTML string to the page.

    3. To create the HTML the easiest method, since you already have the markup you want, is to add that within a template string, and apply the object properties you want displayed at the appropriate places within.

    4. Use insertAdjacentHTML to add the HTML to the page.

    5. Creating properly formatted currency strings can be achieved with Intl.NumberFormat.

    Below is an example on how to build the HTML for one object ("Clue"), and append it to the page. All the CSS is missing (obviously) but I did add one line to show the "line-through" for the non-sale price.

    const data=[{id:1,productName:"Chutes and Ladders",image:"../public/ChutesandLadders.jpg",price:15.75,salePrice:15.75},{id:2,productName:"Monopoly",image:"../public/Monopoly.jpg",price:15.25,salePrice:15.25},{id:3,productName:"Clue",image:"../public/Clue.jpg",price:20,salePrice:15.2},{id:4,productName:"The Game of Life",image:"../public/GameofLife.jpg",price:16,salePrice:10},{id:5,productName:"TRESomme Shampoo",image:"../public/Tresomme.jpg",price:45,salePrice:30},{id:6,productName:"Michael Kors Purse",image:"../public/MichaelKorsPurse.jpg",price:145,salePrice:145},{id:7,productName:"Apple Watch Ultra",image:"../public/AppleWatch.jpg",price:200,salePrice:175}];
    
    // A function that accepts the array of data, a property
    // name, and a query value, and returns the object that matches
    // that condition
    function finder(data, prop, query) {
      return data.find(obj => obj[prop] === query);
    }
    
    // A function to create properly a formatted
    // currency string - pass in a number, a locale
    // (e.g. 'en-GB'), and a currency type
    function toCurrency(number, locale, type) {
      return new Intl.NumberFormat(locale, {
        style: 'currency',
        currency: type }
      ).format(number);
    }
    
    // Find the "Clue" object
    const clue = finder(data, 'productName', 'Clue');
    
    // Create the HTML using the object property values
    // from the "Clue" object
    const html = `
      <div class="badge bg-dark text-white position-absolute" style="top: 0.5rem; right: 0.5rem">Sale</div>  
      <img class="card-img-top" width="450" height="200" src="${clue.image}" alt="..." />         
         <div class="card-body p-4">
            <div class="text-center">
               <h5 class="fw-bolder">${clue.productName}</h5>
                  <div class="d-flex justify-content-center small text-warning mb-2">
                     <div class="bi-star-fill"></div>
                        <div class="bi-star-fill"></div>
                        <div class="bi-star-fill"></div>
                        <div class="bi-star-fill"></div>
                        <div class="bi-star-fill"></div>
                     </div>
                  <span class="text-muted text-decoration-line-through">${toCurrency(clue.price, 'en-GB', 'GBP')}</span>
                  ${toCurrency(clue.salePrice, 'en-GB', 'GBP')}
               </div>
            </div>
            <div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
               <div class="text-center"><a class="btn btn-outline-dark mt-auto" href="#">Add to cart</a></div>
            </div>
         </div>
      </div>
    `;
    
    // Append the HTML to the page
    document.body.insertAdjacentHTML('beforeend', html);
    .text-decoration-line-through { text-decoration: line-through; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search