SyntaxStudy
Sign Up
jQuery jQuery $.getJSON() and JSON APIs
jQuery Beginner 5 min read

jQuery $.getJSON() and JSON APIs

Modern web APIs almost universally return JSON. jQuery's $.getJSON() is a specialised shorthand that performs a GET request and automatically parses the response body as JSON, handing you a ready-to-use JavaScript object in the callback.

How It Works

Internally, $.getJSON(url, data, callback) is equivalent to $.ajax({ url, data, dataType: 'json', success: callback }). Because jQuery sets the Accept: application/json header, well-behaved APIs will also return JSON content-type automatically.

Consuming a Public API

Pair $.getJSON() with a public REST API to pull in live data — weather forecasts, GitHub repository info, or currency exchange rates — and render it dynamically without a page reload.

  • Response is auto-parsed — no JSON.parse() needed
  • Returns a jqXHR object for .done() / .fail() chaining
  • Supports JSONP via callback=? in the URL (legacy cross-origin technique)

When the API returns an error status code (4xx, 5xx), jQuery triggers the .fail() handler, not the success callback, giving you clean separation of the happy path from error handling.

Example
// Fetch JSON from a public API
$.getJSON('https://api.github.com/repos/jquery/jquery', function (repo) {
    $('#repo-name').text(repo.full_name);
    $('#repo-stars').text(repo.stargazers_count + ' stars');
    $('#repo-desc').text(repo.description);
})
.fail(function (xhr) {
    console.error('API error:', xhr.status, xhr.statusText);
});

// With query parameters
$.getJSON('/api/products', { category: 'electronics', limit: 10 })
  .done(function (products) {
      products.forEach(function (p) {
          $('#product-list').append(
              '<div class="product"><h4>' + p.name + '</h4></div>'
          );
      });
  });
Pro Tip

$.getJSON() auto-parses responses — no JSON.parse() needed, and .fail() fires for any 4xx/5xx status.