JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

What is JSON in HTML?

15 April 2025 | Category:

JSON (JavaScript Object Notation) is a data format used for storing and exchanging data. When used in an HTML page, JSON can be loaded and used by JavaScript to display dynamic content on a web page without reloading it.


💡 Why Use JSON in HTML?

  • JSON is lightweight and easy to read/write.
  • It works seamlessly with JavaScript.
  • It’s perfect for loading external data dynamically into HTML (e.g., product lists, user profiles, etc.).

🔹 1. Store JSON Inside HTML

You can store JSON in an HTML file using a <script type="application/json"> tag.

✅ Example:

<!DOCTYPE html>
<html>
<head>
  <title>JSON in HTML</title>
</head>
<body>

<h2 id="username"></h2>

<script id="userData" type="application/json">
  {
    "name": "Alice",
    "age": 25,
    "city": "New York"
  }
</script>

<script>
  const jsonData = document.getElementById("userData").textContent;
  const user = JSON.parse(jsonData);

  document.getElementById("username").textContent = "Name: " + user.name;
</script>

</body>
</html>

🔹 2. Load External JSON File with JavaScript

If you have a .json file, you can load it using the Fetch API.

✅ Example: Load JSON from File

📁 data.json

{
  "title": "Welcome to My Website",
  "description": "This is dynamic content loaded using JSON"
}

📄 index.html

<!DOCTYPE html>
<html>
<head>
  <title>JSON Example</title>
</head>
<body>

<h1 id="title"></h1>
<p id="desc"></p>

<script>
  fetch('data.json')
    .then(res => res.json())
    .then(data => {
      document.getElementById("title").textContent = data.title;
      document.getElementById("desc").textContent = data.description;
    });
</script>

</body>
</html>

🔹 3. Using JSON to Populate HTML Tables

✅ Example:

<!DOCTYPE html>
<html>
<head>
  <title>Users Table</title>
</head>
<body>

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

<script>
  const users = [
    { "name": "John", "age": 30 },
    { "name": "Jane", "age": 25 },
    { "name": "Bob", "age": 40 }
  ];

  const table = document.getElementById("userTable");

  users.forEach(user => {
    const row = table.insertRow();
    row.insertCell(0).textContent = user.name;
    row.insertCell(1).textContent = user.age;
  });
</script>

</body>
</html>

🔄 Summary

TaskMethod
Embed JSON in HTML<script type="application/json">
Load JSON from external filefetch()
Parse JSON stringJSON.parse()
Populate HTML with JSONDOM manipulation + JS loop

📦 Use Cases

  • Load blog articles dynamically
  • Show user info/profile from a JSON API
  • Populate dropdowns, tables, charts
  • Create single-page applications (SPA)