JSON: What It Is, How It Works, and How to Use It
Understanding JSON and Using jQuery to Put It to Work
My apologies for the lapse in posting; I'm in the midst of finishing my first book for Apress (it's called PHP for Absolute Beginners, and should be out later this year), and it's been consuming most of my attention.
This week, however, I want to cover a topic that I feel has become an important part of any developer's toolkit: the ability to load and manipulate JSON feeds from other sites via AJAX.
Many sites are sharing data using JSON in addition to RSS feeds nowadays, and with good reason: JSON feeds can be loaded asynchronously much more easily than XML/RSS.
This article will cover the following:
- What is JSON?
- Why does JSON matter?
- How do we load JSON into a project?
We'll also use our newfound skills with JSON at the end of this project to build a quick app that loads photos from Flickr without requiring a page refresh.
See the Demo | Download the Source
What Is JSON?
JSON is short for JavaScript Object Notation, and is a way to store information in an organized, easy-to-access manner. In a nutshell, it gives us a human-readable collection of data that we can access in a really logical manner.
Storing JSON Data
As a simple example, information about me might be written in JSON as follows:
var jason = {
"age" : "24",
"hometown" : "Missoula, MT",
"gender" : "male"
};
This creates an object that we access using the variable jason. By enclosing the variable's value in curly braces, we're indicating that the value is an object. Inside the object, we can declare any number of properties using a "property-name" : "property-value" pairing, separated by commas.
To access the information stored in jason, we can simply refer to the name of the property we need. For instance, to access information about me, we could use the following snippets:
document.write('Jason is '+jason.age); // Output: Jason is 24
document.write('Jason is a '+jason.gender); // Output: Jason is a male
Storing JSON Data in Arrays
A slightly more complicated example involves storing two people in one variable. To do this, we enclose multiple objects in square brackets, which signifies an array.
For instance, if I needed to include information about myself and my brother in one variable, I might use the following:
var family = [{
"name" : "Jason",
"age" : "24",
"gender" : "male"
},
{
"name" : "Kyle",
"age" : "21",
"gender" : "male"
}];
To access this information, we need to access the array index of the person we wish to access. For example, we would use the following snippet to access info stored in family:
document.write(family[1].name); // Output: Kyle
document.write(family[0].age); // Output: 24
NOTE: This is beneficial if it will be necessary to loop through stored information, as it lends itself to a for loop with an automatically incrementing value.
Nesting JSON Data
Another way to store multiple people in our variable would be to nest objects. To do this, we would create something similar to the following:
var family = {
"jason" : {
"name" : "Jason Lengstorf",
"age" : "24",
"gender" : "male"
},
"kyle" : {
"name" : "Kyle Lengstorf",
"age" : "21",
"gender" : "male"
}
}
Accessing information in nested objects is a little easier to understand; to access information in the object, we would use the following snippet:
document.write(family.jason.name); // Output: Jason Lengstorf
document.write(family.kyle.age); // Output: 21
document.write(family.jason.gender); // Output: male
Nested JSON and arrays can be combined as needed to store as much data as necessary.
Why Does JSON Matter?
With the rise of AJAX-powered sites, it's becoming more and more important for sites to be able to load data quickly and asynchronously, or in the background without delaying page rendering.
Switching up the contents of a certain element within our layouts without requiring a page refresh adds a "wow" factor to our applications, not to mention the added convenience for our users.
Because of the popularity and ease of social media, many sites rely on the content provided by sites such as Twitter, Flickr, and others. These sites provide RSS feeds, which are easy to import and use on the server-side, but if we try to load them with AJAX, we run into a wall: we can only load an RSS feed if we're requesting it from the same domain it's hosted on.
An attempt to load my Flickr account's RSS feed via jQuery's $.ajax() method results in the following JavaScript error:
[Exception... "Access to restricted URI denied" code: "1012"
nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)"
location: "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js Line: 19"]
JSON allows us to overcome the cross-domain issue because we can use a method called JSONP that uses a callback function to send the JSON data back to our domain. It's this capability that makes JSON so incredibly useful, as it opens up a lot of doors that were previously difficult to work around.
How Do We Load JSON into a Project?
One of the easiest ways to load JSON data into our web applications is to use the $.ajax() method available in the jQuery library. The ease of retrieving data will vary based on the site providing the data, but a simple example might look like this:
$.ajax(
type:'GET',
url:"http://example.com/users/feeds/",
data:"format=json&id=123",
success:function(feed) {
document.write(feed);
},
dataType:'jsonp'
);
This example would request the latest feed items in JSON format and output them to the browser. Obviously, we wouldn't want to output raw JSON data to the browser, but this example shows the basics of loading JSON from an external source.
A Practical Example: Loading Flickr Streams with JSON and jQuery
See the Demo | Download the Source
To show how JSON works in a real-world example, let's load photos from Flickr using jQuery and the JSON version of Flickr's "Latest" photo feed.
Step 1: Create the AJAX Request
Flickr's photostream feeds are relatively easy to access. All users have a unique ID number, which we will send as part of the request to this URL.
http://api.flickr.com/services/feeds/photos_public.gne
The request we need to send asks for the latest photos from the user in question, along with flags asking for a JSON-formatted response. The request we need to send will look like this:
id=XXXXXXXX@NXX&lang=en-us&format=json&jsoncallback=?
In the above example, XXXXXXXX@NXX needs to be replaced with the user's ID.
We'll be writing a function, so the user's ID will be passed as an argument called flickrID. Our function will be called loadFlickr(). Let's create the function that will load our JSON response:
function loadFlickr(flickrid)
{
$('#feed').html('<span><img src="images/lightbox-ico-loading.gif" /></span>');
$.ajax({
type:'GET',
url:"http://api.flickr.com/services/feeds/photos_public.gne",
data:"id="+flickrid+"&lang=en-us&format=json&jsoncallback=?",
success:function(feed) {
// Do something with the response
},
dataType:'jsonp'
});
}
The returned JSON data will look something like this (note that I've removed all but one of the returned photos for the sake of brevity):
({
"title": "Uploads from ennuidesign",
"link": "http://www.flickr.com/photos/ennuidesign/",
"description": "",
"modified": "2009-03-17T03:53:36Z",
"generator": "http://www.flickr.com/",
"items": [
{
"title": "This Is How You Get People to Talk About You",
"link": "http://www.flickr.com/photos/ennuidesign/3361269251/",
"media": {"m":"http://farm4.static.flickr.com/3470/3361269251_9c55e6dc24_m.jpg"},
"date_taken": "2009-03-16T21:53:36-08:00",
"description": "<p><a href=\"http://www.flickr.com/people/ennuidesign/\">ennuidesign<\/a> posted a photo:<\/p> <p><a href=\"http://www.flickr.com/photos/ennuidesign/3361269251/\" title=\"This Is How You Get People to Talk About You\"><img src=\"http://farm4.static.flickr.com/3470/3361269251_9c55e6dc24_m.jpg\" width=\"240\" height=\"180\" alt=\"This Is How You Get People to Talk About You\" /><\/a><\/p> <p>A guy I know, Trevor Gnauck, made this custom pint glass for me. He runs a company called <a href=\"http://www.bluedragonllc.com/\">Blue Dragon Custom Laser Engraving<\/a> with his family, and he had no reason whatsoever to do anything nice for me.<br /> <br /> He did, though, and look how cool that is! I can now drink a beer out of my own likeness.<br /> <br /> I know it wasn\'t his intention, but this is how you get people to talk about you. Unprovoked kindness will always inspire kindness in return, and the power of a kind gesture should never be overlooked.<\/p>",
"published": "2009-03-17T03:53:36Z",
"author": "nobody@flickr.com (ennuidesign)",
"author_id": "29080075@N02",
"tags": "gift ennuidesign trevorgnauck bluedragoncustomlaserengraving"
}
// The rest of the photo entries go here...
]
})
Step 2: Process the JSON Data
What we're going to do is display the thumbnails of the latest 16 photos, which will link to the medium-sized display of the image.
The Flickr JSON is a little confusing, and it doesn't provide a direct link to the thumbnail version of our photos, so we'll have to use some trickery on our end to get to it, which we'll cover in just a moment.
Each photo entry is stored in an array called items, which we access in our AJAX call using feed.items. To get to the data about each entry, we'll loop through the items until we've either hit the last available photo or 16 total photos; whichever comes first.
Let's modify our function and set up the loop:
function loadFlickr(flickrid)
{
// Display a loading icon in our display element
$('#feed').html('<span><img src="images/lightbox-ico-loading.gif" /></span>');
// Request the JSON and process it
$.ajax({
type:'GET',
url:"http://api.flickr.com/services/feeds/photos_public.gne",
data:"id="+flickrid+"&lang=en-us&format=json&jsoncallback=?",
success:function(feed) {
// Create an empty array to store images
var thumbs = [];
// Loop through the items
for(var i=0, l=feed.items.length; i < l && i < 16; ++i)
{
// Process each image
}
// Display the thumbnails on the page
},
dataType:'jsonp'
});
}
The element we're interested in is the "m" element stored within the "media" element. This can be accessed within our loop using feed.items[i].media.m. We're going to run a regular expression on this value to get both the medium and thumbnail image paths, which we'll assemble into a linked thumbnail image.
Then, we'll push the newly assembled HTML into the array of thumbs we created. After we've finished the loop, we'll combine all the images into one string of HTML and replace the contents of our display element with the loaded thumbnails.
Let's add this functionality to our script:
function loadFlickr(flickrid)
{
// Display a loading icon in our display element
$('#feed').html('<span><img src="images/lightbox-ico-loading.gif" /></span>');
// Request the JSON and process it
$.ajax({
type:'GET',
url:"http://api.flickr.com/services/feeds/photos_public.gne",
data:"id="+flickrid+"&lang=en-us&format=json&jsoncallback=?",
success:function(feed) {
// Create an empty array to store images
var thumbs = [];
// Loop through the items
for(var i=0, l=feed.items.length; i < l && i < 16; ++i)
{
// Manipulate the image to get thumb and medium sizes
var img = feed.items[i].media.m.replace(
/^(.*?)_m\.jpg$/,
'<a href="$1.jpg"><img src="$1_s.jpg" alt="" /></a>'
);
// Add the new element to the array
thumbs.push(img);
}
// Display the thumbnails on the page
$('#feed').html(thumbs.join(''));
// A function to add a lightbox effect
addLB();
},
dataType:'jsonp'
});
}
Note that I've also added a function called addLB() to the end of this function; this adds the lightbox effect to our thumbnails, which is purely for aesthetics.
Step 3: Call Our Function
At this point, we're ready to call our function. To load my Flickr stream, we would need to call our function as follows:
loadFlickr("29080075@N02");
The example posted will pull multiple users' photostreams into the containing box without causing a page refresh. Look at the source code on the demo to see how it was done.
NOTE: Keep in mind that this demo was to show how to load JSON data, and not on how to implement the code to call the function. The JavaScript calls are inline, which should NOT be used in a production script.
See the Demo | Download the Source
Summary
Have you used JSON before? Is there anything you'd like to clarify or see further clarified about JSON? Let me know in the comments!
Comments for This Entry
Great site, great writeup!
great JQUERY manipulation.....very useful script Jason.. Good job.
I found this a great intro to JSON, thanks for the info.
nice article! it answer me some questions
but, i'm not a developer or programmer... when i see the codes above, I see like jquery plugins looks like.
Jquery = JSON, Jquery is a kind of JSON, jQuery use JSON to work.... ¿?¿?
thanks in advance!
very informative for beginners..
gr8 one... to start learning JSON
@dlv:
jQuery and JSON are different. Both are based on JavaScript, so they work together.
JSON is a way to store data, and jQuery is a JavaScript framework that provides a simpler way to perform many complex JavaScript tasks, such as loading the response from a website in JSON.
Make sense?
@everyone else:
Thanks so much for the kind words!
thanks Jason ! now it's more clear for me!
Great article!
"Keep in mind that this demo was to show how to load JSON data, and not on how to implement the code to call the function. The JavaScript calls are inline, which should NOT be used in a production script."
Can you elaborate more on this please?
Thanks
This is great for newbies like me to get to know JSON. Many thanks!
@5h4rk:
The links in the demo are set up with JS as the href value (i.e. href="javascript:loadFlickr(XXXXXXXX@NXX)"). This is bad practice, because if the user has JS turned off, the link is completely useless. JS links are bad for SEO, too.
A better approach would be to link to the user's Flickr page, then use JS to add the function call to the link and return false, which will prevent the link from firing.
You can use a class for this, such as:
Jason Lengstorf
That does the same thing as having the JS inline, but it makes the link useful to search engines and users without JS turned on.
Does that clear it up for you?
What's the difference between using $.ajax() and $.getJSON() ?
@Bryce:
$.getJSON() is a shortcut for $.ajax() that's specialized. So, the difference is that $.ajax() works for any AJAX request, and $.getJSON() will only work if you're requesting a JSON response.
In the above example, we certainly could have used $.getJSON(). I used $.ajax() out of habit.
Thanks Jason, it makes more sense now.
very good article.. thanks.
One thing to note is that your AJAX call specifically adds the data type JSONP and the URL defines the callback function. If the web service you are using doesn't allow for specifying a callback function, then cross-domain requests won't work.
Excellent tut, simple and to the point. Thanks for sharing!
Great article on JSON and integrating with jQuery! We built a tool to interact with JSON and easily view/edit/manipulate it on any platform (OS X, Linux, or windows) via Adobe AIR and JavaScript.
Check it out:
http://www.jsonpro.com
Great article..
very useful for me :)
thx alot..
super
I'd like to use Json with netbeans, how does it works?
@Carmen:
You shouldn't need to add anything to NetBeans to develop apps that use JSON. Syntax highlighting should work right out of the box.
This is inspiring! Thanks for the awesome post! : )
Thanks for the tutorial. Well written and easy to understand.
Thanks for making JSON easy to understand. It really helped me.
Hey Jason,
Thanks you for this tutorial :) it really helps .keep it up
wish u loads of gud wishes
Mmm - JQuery. The comments are almost as informative as the article. Thanks for taking the time to put this tutorial together.
Mmm - JQuery. The comments are almost as informative as the article. Thanks for taking the time to put this tutorial together.
Ahh! Sorry for the double post (although I have no idea how that happened.)
Post a Comment
Want to show your face? Get a gravatar!