Posted by Jason Lengstorf in Development
This week 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 use JSON in 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.
What Is JSON?
Storing JSON Data
As a simple example, information about me might be written in JSON as follows:
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
"name": "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:
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:
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
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:
Accessing information in nested objects is a little easier to understand; to access information in the object, we would use the following snippet:
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
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:
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
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.
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:
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:
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):
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:
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:
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:
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!