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.
$.getJSON() is a shorthand AJAX method$.ajax() gives full request controlYou call $.getJSON() with a URL and a callback function. The callback receives parsed JSON data that can be looped and rendered.
// 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>
// 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>
// 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>
The JSON data is fetched asynchronously, looped using $.each(), and converted into HTML elements that are injected into the page.
console.log()dataType:"json" in AJAXbooks.json file and display titles