JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JSON HTML


JSON is an essential tool for dynamically displaying data on web pages. By combining JSON with HTML and JavaScript, you can fetch data from a server or local files and render it directly in your web page without hardcoding values. This approach makes web pages dynamic, responsive, and interactive.

Why Use JSON with HTML?

Using JSON with HTML allows you to:

  • Display dynamic content without manually writing HTML.

  • Fetch data from APIs or local JSON files.

  • Update web pages in real-time with JavaScript.

  • Handle structured data such as tables, lists, or forms.

Loading JSON Data

There are two common ways to load JSON data in HTML pages:

1. Local JSON File

Suppose you have a file data.json:

[
  { "name": "Vicky", "age": 28, "city": "Mumbai" },
  { "name": "Sanjana", "age": 26, "city": "Delhi" }
]

You can fetch this file in JavaScript:

<!DOCTYPE html>
<html>
<head>
  <title>JSON HTML Example</title>
</head>
<body>
  <div id="users"></div>

  <script>
    fetch('data.json')
      .then(response => response.json())
      .then(data => {
        let container = document.getElementById('users');
        data.forEach(user => {
          container.innerHTML += `<p>${user.name} - ${user.age} - ${user.city}</p>`;
        });
      });
  </script>
</body>
</html>

Explanation:

  • fetch() retrieves the JSON file.

  • response.json() converts it into a JavaScript array.

  • forEach() loops through each object to create HTML content dynamically.

2. JSON from JavaScript

You can also define JSON data directly in your JavaScript:

<script>
  let users = [
    { name: "Vicky", age: 28, city: "Mumbai" },
    { name: "Sanjana", age: 26, city: "Delhi" }
  ];

  let container = document.getElementById('users');
  users.forEach(user => {
    container.innerHTML += `<p>${user.name} - ${user.age} - ${user.city}</p>`;
  });
</script>

This is useful for testing or small datasets without a server.

Creating HTML Tables from JSON

JSON arrays are perfect for generating tables dynamically:

<table border="1" id="userTable">
  <tr>
    <th>Name</th>
    <th>Age</th>
    <th>City</th>
  </tr>
</table>

<script>
  let users = [
    { name: "Vicky", age: 28, city: "Mumbai" },
    { name: "Sanjana", age: 26, city: "Delhi" }
  ];

  let table = document.getElementById('userTable');

  users.forEach(user => {
    let row = table.insertRow();
    row.insertCell(0).innerHTML = user.name;
    row.insertCell(1).innerHTML = user.age;
    row.insertCell(2).innerHTML = user.city;
  });
</script>

Explanation:

  • insertRow() creates a new row in the table.

  • insertCell() adds cells to the row with data from JSON.

  • This approach is widely used for dashboards, reports, and admin panels.

Creating Lists from JSON

JSON can also generate unordered or ordered lists:

<ul id="userList"></ul>

<script>
  let users = [
    { name: "Vicky", age: 28 },
    { name: "Sanjana", age: 26 }
  ];

  let list = document.getElementById('userList');

  users.forEach(user => {
    let li = document.createElement('li');
    li.textContent = `${user.name} (${user.age})`;
    list.appendChild(li);
  });
</script>
  • createElement() creates an li element.

  • appendChild() adds it to the ul.

  • Dynamic lists are useful for menus, task lists, or user comments.

Using JSON with Forms

You can use JSON to populate dropdowns dynamically:

<select id="citySelect"></select>

<script>
  let cities = [
    { id: 1, name: "Mumbai" },
    { id: 2, name: "Delhi" },
    { id: 3, name: "Bangalore" }
  ];

  let select = document.getElementById('citySelect');

  cities.forEach(city => {
    let option = document.createElement('option');
    option.value = city.id;
    option.textContent = city.name;
    select.appendChild(option);
  });
</script>
  • This allows your forms to adapt automatically when data changes.

  • You don’t need to manually update HTML every time.

Fetching JSON from APIs

You can combine HTML and JSON to display live API data:

<div id="userContainer"></div>

<script>
  fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(users => {
      let container = document.getElementById('userContainer');
      users.forEach(user => {
        container.innerHTML += `<p>${user.name} - ${user.email}</p>`;
      });
    });
</script>
  • JSON fetched from APIs can populate tables, cards, lists, or forms.

  • This technique is standard in modern web development.

Tips for Using JSON with HTML

  1. Use innerHTML cautiously — for large datasets, consider creating elements dynamically instead of concatenating strings.

  2. Sanitize data from external sources to avoid XSS attacks.

  3. Keep JSON structured — nested objects and arrays are easier to handle with JavaScript.

  4. Use templates for repeated HTML structures (like cards or table rows).

Real-World Example: User Card

<div id="cards"></div>

<script>
  let users = [
    { name: "Vicky", age: 28, city: "Mumbai" },
    { name: "Sanjana", age: 26, city: "Delhi" }
  ];

  let container = document.getElementById('cards');

  users.forEach(user => {
    let card = `<div style="border:1px solid #ccc; padding:10px; margin:5px;">
                  <h3>${user.name}</h3>
                  <p>Age: ${user.age}</p>
                  <p>City: ${user.city}</p>
                </div>`;
    container.innerHTML += card;
  });
</script>
  • Each user gets a dynamic card.

  • Styling can be enhanced with CSS or frameworks like Bootstrap.

Summary of the Tutorial

  • JSON allows dynamic content generation in HTML pages.

  • Fetch data from local files or APIs and render it using JavaScript.

  • Use loops to create tables, lists, forms, or cards from JSON.

  • Dynamic content improves maintainability and scalability of web pages.

  • Sanitize and structure data for safe and efficient rendering.

Mastering JSON with HTML is essential for interactive web pages, dashboards, and modern front-end development.


Practice Questions

  1. Create a JSON array of three users (name, age, city) and display each user’s name and city in <p> tags inside a <div>.

  2. Fetch data from a local JSON file (data.json) containing a list of products and display each product’s name and price in the HTML page.

  3. Create a JSON array of tasks and dynamically generate an unordered list <ul> showing all task names.

  4. Create a JSON array of cities and populate a <select> dropdown with city names and their IDs as values.

  5. Use a JSON array of students and generate a table showing their name, age, and grade.

  6. Dynamically create a set of cards from a JSON array of users where each card shows name, age, and city.

  7. Fetch JSON data from https://jsonplaceholder.typicode.com/users and display each user’s name and email in <p> tags.

  8. Create a JSON array of books with title and author, and display them in a table where the first row is headers.

  9. Update a <div> dynamically with JSON data every 5 seconds to simulate a live feed (e.g., messages or notifications).

  10. Create a JSON array with nested objects for employees (name, department, contact object with email and phone) and display each employee’s details in an HTML card.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top