$.getJSON
Fetch JSON data and use it as a JavaScript object.
Syntax
$.getJSON(url, function (data) { ... });$.getJSON(url, callback) requests a URL and automatically parses the JSON response into a JavaScript object or array.
$.getJSON("/api/users", function (users) {
$.each(users, function (i, user) {
$("#list").append("" + user.name + " ");
});
});It is a shortcut for $.ajax() with dataType: "json".
Example
Loading editor…
Press Run to see the result.
When to use it
- A currency converter calls $.getJSON('/api/rates') to retrieve the latest exchange rates and populates a select menu.
- A public GitHub stats widget fetches repository data from the GitHub JSON API with $.getJSON and renders stars and forks.
- A product listing renders a card for each item in a JSON array returned by $.getJSON('/api/products').
More examples
Fetch and render a JSON array
$.getJSON() automatically parses the response as JSON; $.each() iterates the array to build the list.
<ul id="products"></ul>
<button id="loadProducts">Load products</button>
<script>
$(function () {
$("#loadProducts").click(function () {
$.getJSON("/api/products", function (items) {
$.each(items, function (i, item) {
$("#products").append("<li>" + item.name + " — $" + item.price + "</li>");
});
});
});
});
</script>Fetch JSON with query parameters
Appending the repo name to the URL path sends the GET request to GitHub's public API and displays star count.
<input id="repoInput" placeholder="user/repo" value="jquery/jquery" />
<button id="fetchRepo">Fetch</button>
<p id="repoInfo"></p>
<script>
$(function () {
$("#fetchRepo").click(function () {
var repo = $("#repoInput").val();
$.getJSON("https://api.github.com/repos/" + repo, function (data) {
$("#repoInfo").text(data.full_name + " — ★ " + data.stargazers_count);
});
});
});
</script>Handle getJSON error with .fail()
.fail() on the returned Deferred catches network errors or non-200 responses so the UI can degrade gracefully.
<button id="getData">Load config</button>
<p id="out"></p>
<script>
$(function () {
$("#getData").click(function () {
$.getJSON("/api/config")
.done(function (cfg) {
$("#out").text("Theme: " + cfg.theme);
})
.fail(function () {
$("#out").text("Failed to load config.");
});
});
});
</script>
Discussion