← Back to Chapters

Read JSON Data with jQuery

? Read JSON Data with jQuery

? Quick Overview

jQuery provides a simple way to read JSON data using $.getJSON() or $.ajax(). This is commonly used when fetching data from APIs or local JSON files and displaying it dynamically on a webpage.

? Key Concepts

  • JSON is automatically parsed into JavaScript objects
  • $.getJSON() is a shorthand AJAX method
  • $.ajax() gives full request control

⚙️ Syntax / Theory

You call $.getJSON() with a URL and a callback function. The callback receives parsed JSON data that can be looped and rendered.

? Example 1: Load JSON from Local File

? View Code Example
// Load local JSON file and display users
[
{ "id": 1, "name": "Alice", "email": "alice@example.com" },
{ "id": 2, "name": "Bob", "email": "bob@example.com" },
{ "id": 3, "name": "Charlie", "email": "charlie@example.com" }
]

<div id="users"></div>

<script>
$(document).ready(function(){
$.getJSON("users.json",function(data){
let output="<ul>";
$.each(data,function(index,user){
output+="<li>"+user.name+" ("+user.email+")</li>";
});
output+="</ul>";
$("#users").html(output);
});
});
</script>

? Example 2: Load JSON from API

? View Code Example
// Fetch JSON data from public API
<div id="posts"></div>

<script>
$(document).ready(function(){
$.getJSON("https://jsonplaceholder.typicode.com/posts?_limit=5",function(posts){
let html="";
$.each(posts,function(i,post){
html+="<h4>"+post.title+"</h4>";
html+="<p>"+post.body+"</p><hr>";
});
$("#posts").html(html);
});
});
</script>

?️ Example 3: Using $.ajax()

? View Code Example
// Use $.ajax for more flexibility
<div id="products"></div>

<script>
$(document).ready(function(){
$.ajax({
url:"products.json",
method:"GET",
dataType:"json",
success:function(data){
let table="<table border='1'><tr><th>ID</th><th>Name</th><th>Price</th></tr>";
$.each(data,function(i,product){
table+="<tr><td>"+product.id+"</td><td>"+product.name+"</td><td>"+product.price+"</td></tr>";
});
table+="</table>";
$("#products").html(table);
}
});
});
</script>

? Live Output / Explanation

The JSON data is fetched asynchronously, looped using $.each(), and converted into HTML elements that are injected into the page.

? Use Cases

  • Displaying user lists
  • Showing API-driven dashboards
  • Rendering product catalogs dynamically

✅ Tips & Best Practices

  • Inspect JSON using console.log()
  • Always set dataType:"json" in AJAX
  • Use proper servers instead of file system

? Try It Yourself

  • Create a books.json file and display titles
  • Fetch live crypto prices from an API
  • Render nested JSON categories