Load JSON data with jQuery
Posted February 23rd, 2010 in Javascript (Updated March 2nd, 2010)
JSON data can be retrieved using AJAX from a server either using jQuery's .ajax() function or the shorthand $.getJSON() function. If you have retrieved a JSON string without having jQuery decode it automatically using one of these functions, the string can also be parsed into a regular data array using the $.parseJSON() function.
$.getJSON()
The easiest way to load some JSON data in jQuery is with the $.getJSON() function and using the callback to do something with the data. If the URL to get the JSON data is at /json/somedata.json then it can be retrieved and something done with it like so:
$.getJSON('/json/somedata.json', function(data) {
// do something with the data here
});
$.ajax()
The above is a shortcut to the $.ajax() method. If you needed to set some of the other AJAX properties use the $.ajax() function instead. The following is the equivilent of the above:
$.ajax({
dataType: 'json',
success: function(data) {
// do something
},
url: '/json/somedata.json'
});
$.parseJSON();
Finally, a JSON encoded string can be converted to a Javascript array using $.parseJSON(). If "string" in the example below contains a JSON string it can be converted to an array like so:
data = $.parseJSON(string);
The string could potentially be retrived using AJAX from the server as plain text, and then converted to an array like this, although normally you would use the dataType 'json' and leave it up to jQuery to do it for you:
$.ajax({
dataType: 'text',
success: function(string) {
data = $.parseJSON(string);
// do something
},
url: '/json/somedata.json'
});
Encoding JSON data with PHP
This post has been followed up showing how to load JSON data with jQuery, PHP and MySQL.
Related posts:
- Load JSON data with jQuery, PHP and MySQL (Tuesday, March 2nd 2010)
- Converting an array to JSON data with PHP (Monday, March 1st 2010)
- Dynamically load a Javascript file with jQuery (Tuesday, February 16th 2010)
- Loading content with jQuery AJAX - selecting the element to inject (Sunday, January 18th 2009)
- Loading content with jQuery AJAX (Wednesday, January 14th 2009)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

