Guide to Fetching JSON Data in JavaScript

Jan 25, 2025

Tutorial: Fetching Data from a JSON File with JavaScript

Overview

  • Objective: Fetch data from a JSON file and display it in a table using JavaScript and the fetch method.
  • End result: A table of products displayed in the browser.

Products Data

  • Products stored in products.json
  • Structure of products.json:
    • Contains an array of objects (products)
    • Each product has the following properties:
      • id
      • name
      • price
      • inventory
      • productCode
      • image (associated with an image file in the product images folder)

Required Files

  • JavaScript file (blank)
  • HTML file (index file with basic structure)
  • CSS file (style.css, not covered in the tutorial)

Step-by-Step Coding Guide

1. Setting Up the HTML

  • Inside the <body> tags of the index file:
    • Create a <table> element
    • Split the table into two sections:
      • Table Head: Contains the column headers
      • Table Body: Will be populated with products via JavaScript
    • Add a data-output id to the table body for targeting in JavaScript

2. JavaScript: Fetching the JSON Data

  • Use the fetch method to send a request to fetch the JSON file.
  • Pass the file name as an argument to fetch.
  • Use .then() method to handle the server's response:
    • Convert the response to JSON using .json() method
    • Use another .then() to access the products data

3. Populating the Table

  • Access the table's body element and store it in a variable called placeholder.
  • Initialize an empty string variable out to hold the products data.
  • Use a for...of loop to iterate through the products array:
    • Append each product to the out variable using template literals (backticks)
    • Include the following in each row of the table:
      • Product's image
      • Product's name
      • Product's price
      • Product's inventory
      • Product's code

4. Finalizing the Display

  • Populate the table body with the out variable containing all the products.
  • Reload the page to see the filled table.

Conclusion

  • Reminder to download the source code from the instructor's website.
  • Encouragement to subscribe for more videos.
  • Thanks for watching!