jQuery API

jQuery.getJSON()

jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] ) Returns: jqXHR

Description: Load JSON-encoded data from the server using a GET HTTP request.

  • version added: 1.0jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )

    urlA string containing the URL to which the request is sent.

    dataA map or string that is sent to the server with the request.

    success(data, textStatus, jqXHR)A callback function that is executed if the request succeeds.

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

Data that is sent to the server is appended to the URL as a query string. If the value of the data parameter is an object (map), it is converted to a string and url-encoded before it is appended to the URL.

Most implementations will specify a success handler:

$.getJSON('ajax/test.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

This example, of course, relies on the structure of the JSON file:

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}

Using this structure, the example loops through the requested data, builds an unordered list, and appends it to the body.

The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.

As of jQuery 1.5, the success callback function receives a "jqXHR" object (in jQuery 1.4, it received the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.

JSONP

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

The jqXHR Object

As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.getJSON() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). For convenience and consistency with the callback names used by $.ajax(), it provides .error(), .success(), and .complete() methods. These methods take a function argument that is called when the request terminates, and the function receives the same arguments as the correspondingly-named $.ajax() callback.

The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including $.getJSON(), to chain multiple .success(), .complete(), and .error() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });

Additional Notes:

  • Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
  • Script and JSONP requests are not subject to the same origin policy restrictions.

Examples:

Example: Loads the four most recent cat pictures from the Flickr JSONP API.

<!DOCTYPE html>
<html>
<head>
  <style>img{ height: 100px; float: left; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div id="images">

</div>
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "cat",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#images");
      if ( i == 3 ) return false;
    });
  });</script>

</body>
</html>

Demo:

Example: Load the JSON data from test.js and access a name from the returned JSON data.

$.getJSON("test.js", function(json) {
   alert("JSON Data: " + json.users[3].name);
 });

Example: Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.

$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
    alert("JSON Data: " + json.users[3].name);
    });

Support and Contributions

Need help with jQuery.getJSON() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to jQuery.getJSON()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • Keo

    For others that might be having trouble with the recent strict changes this {Animal:”DOG”,Name:”Fido”} must now be {“Animal”:”DOG”,”Name”:”Fido”}.
    Notice the extra quotes around the field names now that are required.

  • Anonymous

    There is something that changed from previous versions here.

    For the following code:

    jQuery.getJSON(‘/any/url’,
    { ‘conc’:[0, 5, 10], ‘reads’:[0, 5, 10]});

    One used to get a url such as “/any/url?conc=0&conc=5&conc=10&reads=0&reads=5&reads=10″ but now with 1.4.1 we’re getting something like “/any/url?conc[]=0&conc[]=5&conc[]=10&reads[]=0&reads[]=5&reads[]=10″, so instead of variables with the correct names, now we have those extra brackets.

    How can we revert to the old behavior?

    • http://www.learningjquery.com/ Karl Swedberg
    • http://profiles.yahoo.com/u/BIKXVCYBQYHCNRVUTPKQEAZZCY tXK

      But the first behavior is just..wrong. Why would you want to disregard everything but the last value of the arrays ?

      • Anonymous

        It didn’t discard everything but the last. I got an array without the brackets on the name of the variable. Except for the wrong variable name that is obtained in the new case, it works exactly the same and perfectly well.

  • Diego

    I’ve been having trouble with this function. The callback does not execute when I use $.getJSON OR $.ajax with dateType:’json’. The data returned is an array, exactly like this:
    [/* some comment */
    {name:'John'},
    {name:'Mark'},
    ...
    {name:'Luke'}]

    • http://www.learningjquery.com/ Karl Swedberg

      You’re probably getting a JSON parse error, since you don’t appear to be using well-formed JSON. See json.org for details.

      • Diego

        Thanks for the help Karl. That solved my problem. For future reference – in case somebody has a similar problem – this is the JSON I’m working with (after corrections from my original post):
        [{"name":"John"},{"name":"Mark"}, ... {"name":"Luke"}]

  • Anonymous

    If I’m polling w/ $.getJSON(), chrome reports that the URI i’m getting is a resource – over and over. Never lets these go. How can I force this resource to be released every time?

  • Anonymous

    {‘name’:'balaji’} — Why this is not working?
    But when we use double quotes (“), it works. {“name”:”balaji”} works.

    Any reason?

    • Walrus

      JSON format requires that property names are surrounded by double qoutes. Single qoutes are not allowed.

  • http://www.beweb.co.nz/ mike nelson

    Hi Karl, can you please update the documentation to specifically point out the change between jQuery 1.3.x and 1.4.x which tightens up on the json format. Specifically call out the two major gotchas (1) requiring double quotes instead of single quotes, and (2) even property names need quoting eg { success: true } should now be { “success”: true }.

    Although some dudes went off and “standardised” the json format the rest of us thought it was exactly what it said on the tin – javascript object notation – ie any valid javascript object syntax would be valid. So I am sure many people have this same problem and as you point out it fails silently so this is going to be a common pitfall.

  • Steven Wright

    My understanding is that the callback only fires if the request succeeds. But in the following case it actually appears to be firing before the request returns. If dump json to the console it is undefined. If fetch that URL with a browser it returns the json, but it takes a while. Is there a timeout of some sort?

    // Get the Subscriber Id
    var s = new Date();
    $.getJSON(service_url + 'get_subscriber_id', {
    mac_address: mac_address,
    ts: s.getTime()
    }, function(json){
    url_params.subscriber_id = json.SubscriberId;
    $.get_callerid_history();
    });

  • wolframarnold

    I found the explanation on the JSONP protocol missing a key point: The success callback will NOT be invoked on return from the server. Because this is not a traditional XmlHttpRequest, but instead the server request is made by inserting a script tag. So, the before and success callbacks of the .ajax function are NOT invoked. Only the complete callback is invoked, but that one is not exposed here in getJSON, so you need to call .ajax directly with:
    $.ajax( {
    url: 'http://…',
    dataType: 'jsonp',
    complete: function(xmlHttpReq, textStatus) {…}
    });

  • Anonymous

    Hi,

    I was wondering why this ajax call was allowed calling http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?
    which is on a different domain. But it works.

    Normally cross-domain calls are not permitted right?

    Thanks

    • http://www.learningjquery.com/ Karl Swedberg

      That’s right. It’s using JSONP. The brief paragraph mentioning that above did seem a little too easy to overlook, so I added a subheading. Hope that helps.

  • http://paulisageek.com Paul Tarjan

    Is there a url that matches the getJSON parsing routine to help me debug JSON encoding errors?

    • http://paulisageek.com Paul Tarjan

      I didn't find anything, so I wrote a quick one:

      http://paulisageek.com/json_validator/

    • aowie1
      • Dayton

        Found this before coming here. Response was “Valid JSON”, but still failing silently: I loaded up some sample data last night and that broke it, but works for other data sets. Surely there isn't a problem with a JSON array of just 14 data rows?
        Wondering too, as I am using custom code to build up JSON, is there a recommended PHP library other than getting into changing the server build? You find a ton of stuff, but it's complex enough and doesn't seem a good idea to trust anonymous code…

  • http://twitter.com/lenscraft Ron Lussier

    Is there a way to know if the request fails?

    • Steve

      “As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently.”

      Though as it works as an ajax call something along the lines of:

      $.getJSON(testurl, function(data) {
      formatting stuffs
      })

      $.ajaxSetup({“error”:function(XMLHttpRequest,textStatus, errorThrown) {
      $('#DIV').html('Error' + textStatus + ' ' + errorThrown);

      }});

      I didn't put much time into the above but the general idea of that works alright.

    • http://code.google.com/p/jquery-jsonp/ jaubourg
  • http://twitter.com/pacosoul Francisco Herrera

    Why i can’t GET the values from this URL:
    http://tinysong.com/s/Beethoven?format=json&limit=1&callback=?
    I tried different ways, and other samples are OK, but specially this not funcs.
    I have a little script:

    $.getJSON(“http://tinysong.com/s/Beethoven?format=json&limit=1&callback=?”,
    function(data){
    $(“#datos”).html(data.Url);
    });

    • Anonymous

      because that url returns an array (note the square brackets that wrap the whole thing), so your callback function would have to be like this

      function(data){
      $(“#datos”).html(data[0].Url);
      }

  • http://911-need-code-help.blogspot.com/ Salman

    When retrieving a JSON feed from Google via Google Data API, Firebug Net inspector shows me that the page is using “OPTIONS” method instead of “GET” method to request the data. Why is that? The request fails with the server returning “Method not allowed” error.

    • Anonymous

      put “callback=?” after the as the last option in the request line. for example:

      $.getJSON(“http://foo.example.com/bar.json?callback=?”, …

      edit: the service you are calling must support JSONP :(

      • Peter

        Ta muchly. Put a few to many hours into this one before trawling the for a similar problem.

  • Poonam Kathuria

    I cannot see the demo result above on this page. Could you please suggest what might be the reason for it?

  • rglaue

    For those who get silent failures on $.getJSON calls.

    Your code:
    $.getJSON(“/path/to/jsonservice?jsoncallback=?”, function yada…)

    The “?” gets replaced with a value by JQuery, which the actual translated request the method ends up making is like:
    $.getJSON(“/path/to/jsonservice?jsoncallback=json1234″, function yada…)

    The jsonservice code then has to wrap the json code in the call back, like so:

    Content-type: text/plainnn
    json1234({ “attr1″ : “value1″ })

    if the 'json1234(…)' does not exist in the json results, the $.getJSON will silently error.

    • http://www.ajinkyakulkarni.com Ajinkya

      Thanks , it really helped. Everyone gave all sorts of JSON examples but no one explained this

    • Reaktor8

      I had 7 hours of trial-and-error, and finally came up with your post which solved everything. I wonder why this extremely important point hasn't been made more clear anywhere :(

      Hardest part was that I was able to monitor with Firebug that request did come back with correct results, but I was unable to call even alert inside function parentheses. REALLY evil silent kill :P

  • Red

    Make sure that you use relative paths. Full paths will cause failure without warning.

    • http://www.learningjquery.com/ Karl Swedberg

      …unless, of course, you're using jsonp.

  • Jcpc91

    hi
    everyone (sorry for my english)
    how handle the code 302 httml error this ocurrs when the session time outs. i have this code
    i'm working in asp.net
    &.getJSON('myhandl.ashx', {p:2, d: 4} , function(data, result) {
    alert(result);
    });
    thanks for u answers.

  • Cyrus841113

    Hi there thanks for all the informative posts. I have been trying to copy the first example (with the cats) onto my local serve. It works fine as long as I am linking to the Flickr JSON feed but if I take the exact same file, save it on my sever and attempt to get JSON link to it, nothing happens. Does anyone know why this is so? Am I doing something wrong? Or does JSON only work for cross domain data transfers?

  • Thomas

    if I request data via $.getJSON('/path/to/xyz',{q: query}); firefox sends a GET-request, MSIE8 sends a POST-request.

    is this a bug or an undocumented feature?

  • Mason000001

    Where is test.js, as referenced in the 2nd and 3rd examples?

    • http://www.learningjquery.com/ Karl Swedberg

      Those are just examples. test.js doesn't really exist. But if they did exist, they would be on the same server and in the same directory as the calling script.

  • Grumpee

    So if I have a URL that passes me back JSON but I have a ? in that URL, its going to fail?

  • teebee

    For a JSONP call immediately above “Additional Notes” it says:
    If the URL includes the string “callback=?” in the URL, the request is treated as JSONP instead.
    BUT in the Flickr example the url string is “&jsoncallback=?”

    What is the correct syntax?

    • teebee

      I found other documentation plus experimentation shows “&callback=?” is the correct syntax. (Not to mention other posts)

      • http://www.learningjquery.com/ Karl Swedberg

        Typically you'll want to use “&callback=?”, as most services look for “callback” in the GET request and use its value as the “wrapper function” name. Some services, however, require a different callback function name. The flickr API, for example, looks for “jsoncallback” instead.

        If you use the low-level jQuery.ajax() method and set the dataType option to “jsonp”, it'll append “&callback=?” to the end of the query string by default — unless you specify a different callback function name with the json option.

        • http://twitter.com/woodywijaya budi wijaya

          can you explain to me, how to get data not use “&callback=?” but using “&callback=json”?
          thx

  • aasensiog
  • Tim Hay (at AusPost)

    In the example with the four images, you use a selector of this form: $(“<img>”). What sort of selector is this? I'm assuming that if a matching element is not found in the page, a new one is generated? or is there some special syntax which recognises when a selector begins with the angle bracket?

    • http://www.learningjquery.com/ Karl Swedberg

      You're right that it creates the element, but it doesn't act as a selector at all (i.e. it doesn't look for the element). Here is the entry for more information:
      http://api.jquery.com/jquery/#jQuery2

  • Jyoti Sahu

    can we get response from any file like php or other by cross domain JSONP or only json format file?

  • Guest

    If the script test.js is cached in the client, will the call to test.js refer the file in client ? or does it load from the server again?

  • Anon

    In more recent versions of jQuery, the callback is passed the XHR object as third argument. (This also applies to other shorthand methods.)

  • Tomazaz

    How to handle server errors with $.getJSON ? For example if server return 500 error instead of jsonp object, how to find that?

  • lordspace

    I was getting “invalid label” error. The solution is to pass the JSON data to the js callback

    Example:
    $results = array(“key” => “value”);
    echo $_GET['callback'] . '(' . json_encode($results) . ')';

    Source:
    http://stackoverflow.com/questions/790910/jquery-getjson-to-external-php-page/790931#790931

  • Whitewizard

    I use $.getJSON to call servlet. But servlet return invalid json. Browser show dialog about the invalid json. how to catch this error and not show dialog?

  • Whitewizard

    I use $.getJSON to call servlet. But servlet return invalid json. Browser show dialog about the invalid json. how to catch this error and not show dialog?

  • http://pulse.yahoo.com/_3CIBFUIC5XT3I5EHTR5HIY6GOE SIMON

    Hello, I''m trying to assign the responseText property of the $.getJSON to an array or variable outside the callback function

    let me illustrate what I mean:

    [CODE]
    var j = $.getJSON('../fxns/status.php',function(jsdata){ window.arr = “something else”});

    alert(j.responseText);
    [/CODE]

    This just shows a blank dialog box.

    Now, the $getJSON() is meant to return a XMLHttpRequest object, but for some reason it's properties are only accessible from inside the call back function, and I can't seem to assign the responseText to any variable outside it.

    even [CODE]alert($.getJSON('../fxns/status.php').responseText);[/CODE] alerts a blank dialog box.

    only when I do this:

    [CODE]
    var j = $.getJSON('../fxns/status.php',function(jsdata){ alert(j.responseText);});
    [/CODE]

    do I get a response.

    Now I wouldn't want to be restricted to using the returned responseText inside the callback function as an elaborate function is quite unmanageable and causes some browsers to crash.

    Any ideas?

    • Jonathan Tucker

      Simon,

      Try declaring a variable at the same scope level as your getJSON call. Inside your callback, assign “data” to that global variable. I'm trying to do something similar to what you are, and am running into this same problem with not being able to access the JSON outside of my callback.

  • Allan Naranjo

    Hi, I've been using XML to transfer data from the server to the client side, however in this new application I'm making I started using JSON, Once I get the JSON I'm using json2.js from json.org to implement the reviver function to serialize the JSON.
    I have my custom classes:
    function MYCLASS(){

    }
    The problem I'm encountering is that once parsed what I'm getting is a generic object, and I want it to be a instance of MYCLASS.
    Anyone knows how to accomplish this?

  • Yun

    In regards to the type of json with test.js as shown in the document, I don't really know how to write the test.js. Could you show me an example that I can imitate it?

    Thank you in advance.

    Yun

  • angel

    Hi,

    am a beginner in JSON.
    I have the menalto gallery 3 where all the pictures are available.
    From there, I want to use the REST api, to retrieve all the images from the albums in the gallery 3.
    Can anyone guide me, its 2 days am looking for this.

    Thanks,
    Angel

  • Adrian

    Documentation should mention that the “data” argument is simply appended to the url as GET arguments, and whether it will be url-encoded by jquery or not. Just saying that the data is “sent to the server” is vague. Say how, and what happens to it before it is sent.

  • Leonidas Liakos

    The rigth URL is http://spatialreference.org/projection/?json={“type”:”Feature“, “geometry”:{“type”:”Point”,”coordinates”:[180000, 4352000]},”properties”:{}}&inref=EPSG:2100&outref=EPSG:4326&callback=project_out

  • Laxmi Varde

    But does server reply in plain json format or it replyies in xml and then xml get converted to json

    laxmi
    http://fundooguru.info

  • Joedzilla

    Hello, thank you for your collaboration, its really simple and clean, but I cant find a way to open the images in a new window, it only open them in self, do you know if there is a way to make images (flickr link of the image) open in a new window, so i can click on any image and remain in mi webpage.
    THanks

  • http://twitter.com/woodywijaya budi wijaya

    can you explain to me what these script meaning?
    tags: “cat”,
    tagmode: “any”,
    format: “json”

    from demo of cat images above,thanks

    • AndiSHFR

      Hi.
      These are the “get” parameters added to the the link to form a complete request.
      This way you can hand over arguments to the server-side script.

      In the above example the complete request looks like:

      http://api.flickr.com/services…

  • Abuse
  • Cwy17173

    good…

  • http://twitter.com/woodywijaya budi wijaya

    i have problem with jquery when access data via json,
    suppose i want to display data from url http://api.facebook.com/method… using json,

    if i ran the script via direct url above its failed,
    when i saved that file as 'fql.query', its work? it is a bug or my mistake? or anyone have idea solve via direct link above

  • CoderNet

    都没看见中国人留言啊 …我的MSN:cwy17173@yahoo.cn

    • http://pulse.yahoo.com/_ZW5YGKTSSGW7544BMZWWQHRUU4 dddd

      给你回个

    • Dovis Cn

      我这块有问题啊,帮帮忙啊~

  • Test

    nice………….

  • Test

    nice………….

  • Dada

    It will be perfect if it supports cross-domain post :)

  • rajunix

    $.getJSON(“http://api.flickr.com/services…=?”,

    in this i need google images so i replace with google URL in this URL so it is not working….plz give me sugistions how to get google images …..thanku

    • Iain

      Your URL is an XML feed, not JSON. Btw, this is a support request. Support requests belong in the forums.

  • Cristi Catea

    why this works: ??

    $.getJSON('json/main_profile.json', function(data) {
    $('#info_title').html(
    '

    ' + “General Information ” + '

    '
    );
    });

    but not this one: ???

    $.getJSON(“http://interfaces-server.insource.local/users/145198″, function(data) {
    $('#info_title').html(
    '

    ' + “General Information ” + '

    '
    );
    });

    the data inside the “main_profile.json” is exactly the same like the one in the link

    • Mitis

      due to browser restrictions perhaps?
      depending from where you are calling, it might be seen as cross-site-scripting vulnerability

  • Venkat7668

    Hi
    Here I'm posting my Issue

    $.getJSON(“http://search.twitter.com/sear…){
    alert(data.results);)}

    When I'm trying to get JSON file from twitter search API I'm getting data is NULL. what is wrong here.