json What it is how it works how to uset

JSON: What It Is, How It Works, & How to Use It

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"
};
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

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
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

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"
}];
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

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
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

 

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"
     }
}
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

 

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
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

 

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" ]
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

 

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'
);
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

 

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
<noscript></noscript>

 

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=?
<noscript></noscript>

 

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="/blog/images/lightbox-ico-loading.gif" alt=""></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'
     });
}
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

 

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 title=" This Is How You Get People to Talk About You " href=" http : //www.flickr.com/photos/ennuidesign/ 3361269251 / "><img src=" http : //farm 4 .static.flickr.com/ 3470 / 3361269251 _ 9 c 55e6 dc 24 _m.jpg " alt=" This Is How You Get People to Talk About You " width=" 240 " height=" 180 "></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" : "[email protected]<script type=" text/javascript ">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l=document.getElementById(" __cf_email__ ");a=l.className;if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script> (ennuidesign)" ,
         "author_id" : "29080075@N02" ,
         "tags" : "gift ennuidesign trevorgnauck bluedragoncustomlaserengraving"
     }
 
     // The rest of the photo entries go here...
 
     ]
} )
<noscript></noscript>

 

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="/blog/images/lightbox-ico-loading.gif" alt=""></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'
     });
}
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

 

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 HTMLand 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="/blog/images/lightbox-ico-loading.gif" alt=""></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="/blog/$1.jpg"><img src="/blog/$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'
     });
}
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

 

Note that I’ve also added a function called addLB() to the end of this function; this adds the lightboxeffect 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" );
view raw gistfile1.js This Gist brought to you by GitHub.
<noscript></noscript>

 

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.

 

 

http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/

你可能感兴趣的:(json)