Parsing JSON with getJSON()
In this page:
What is getJSON()?
$.getJSON() is a shorthand AJAX method built specifically for requesting a URL and automatically parsing the JSON response, so you get back a ready-to-use JavaScript object instead of a raw string. This saves calling JSON.parse() yourself on the response.
Example: What is getJSON()?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$.getJSON("data.php", function(data) {
console.log(data);
});
</script>
</body>
</html>
Read JSON Properties
JSON data usually contains named properties and values, and you access them with normal dot notation once getJSON() has parsed the response, like data.name or data.price. The structure of the object mirrors whatever shape the server's JSON response defined.
Example: Read JSON Properties
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$.getJSON("data.php", function(data) {
console.log(data.name);
});
</script>
</body>
</html>
Work with JSON Arrays
A JSON response can be an array of items rather than a single object, and each() is a natural way to visit every item in that array and act on it individually, such as building a row in a table for each one.
Example: Work with JSON Arrays
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="list"></ul>
<script>
const data = [{name: "Apple"}, {name: "Banana"}];
$.each(data, function(i, item) {
$("#list").append("<li>" + item.name + "</li>");
});
</script>
</body>
</html>
Handle JSON Errors
A JSON request can fail because of network problems or because the server returns something that isn't valid JSON, and chaining .fail() lets you handle that case instead of letting the error pass silently. This is especially important since malformed JSON would otherwise throw a parsing error you'd need to catch separately.
Example: Handle JSON Errors
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$.getJSON("data.php").done(function(data) {
console.log(data);
}).fail(function() {
console.log("Failed to load or parse JSON");
});
</script>
</body>
</html>
Small JSON Project
getJSON is useful for dashboards, lists, profiles, and other pages that receive structured data from an API and need to render it directly into the DOM. It's the most direct route from a JSON API endpoint to visible content on the page.
Example: Small JSON Project
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="profile"></div>
<script>
$.getJSON("data.php", function(data) {
$("#profile").text(data.name);
});
</script>
</body>
</html>
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: