INTRO:-
(JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write.
What Is JSON?
➤ JSON is brief for JavaScript Object Notation, store datas in an organized, easy-to-access manner. during a shell, it provides us with a human-readable assortment of data that we are able to access during an extremely logical manner.
Storing JSON data
➤ As a straightforward example, data concerning Pine Tree State may well be written in JSON as follows:
var Jason = {
"age" : "24",
"hometown" : "Missoula, MT",
"gender" : "male"
};
➤ This creates AN object that we have a tendency to access victimization the variable mythical being. By envelopment the variable’s worth in permed braces, we’re indicating that the worth is AN object. within the item, we are able to declare any variety of properties employing a "name": "value" pairing, separated by commas. To access the data keep in mythical being, we are able to merely discuss with the name of the property we want. as an example, to access data concerning Pine Tree State, we have a tendency to may use the subsequent snippets:
1. document.write('Jason is ' mythical being.age); // Output: mythical being is twenty four
2. document.write('Jason could be a ' mythical being.gender); // Output: mythical being could be a male
Storing JSON data in Arrays
➤ A slightly additional sophisticated example involves storing 2 folks in one variable. To do this, we have a tendency to enclose multiple objects in sq. brackets, that signifies AN array. as an example, if I required to incorporate data concerning myself and my brother in one variable, I would use the following:
var family = [
{
"age" : "24",
"gender" : "male"
"},
{
"age" : "21",
"gender" : "male"
}
];
➤ To access this data, we want to access the array index of the person we have a tendency to want to access. as an example, we might use the subsequent snip to access data keep in the family:
NOTE: this can be helpful if it'll be necessary to loop through keep data because it lends itself to a for loop with AN mechanically incrementing worth.
Nesting JSON data
➤ Another way to store multiple folks in our variable would be to nest objects. To do this, we might produce one thing like the following:
var family = "name" : "Jason Lengstorf",
"age" : "24",
"gender" : "male"
">,
"kyle" : "age" : "21",
"gender" : "male"
">
}
➤ Accessing data in nested objects could be very little easier to understand; to access data within the object, we might use the subsequent snippet:
1. document.write(family.jason.name); // Output: mythical being Lengstorf
2. document.write(family.kyle.age); // Output: twenty one
3. document.write(family.jason.gender); // Output: male
➤ Nested JSON and arrays will be combined pro re nata to store the maximum amount data as necessary.
Why will JSON Matter?
➤ With the increase of AJAX-powered sites, it’s changing into additional and additional vital for sites to be able to load data quickly and asynchronously, or within the background while not delaying page rendering. shift up the contents of a definite part among our layouts while not requiring a page refresh adds a “wow” issue to our applications, to not mention the extra convenience for our users. as a result of the recognition and simple social media, several sites think about the content provided by sites like Twitter, Flickr, and others. These sites offer RSS feeds, that ar simple to import and use on the server-side, however if we have a tendency to attempt to load them with mythical being, we have a tendency to run into a wall: we are able to solely load AN RSS feed if we’re requesting it from constant domain it’s hosted on. a shot to load my Flickr account’s RSS feed via jQuery’s $.ajax() technique leads to the subsequent 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 permits us to beat the cross-domain issue as a result of we are able to use a way known as JSONP that uses a recall perform to send the JSON data back to our domain. It’s this capability that produces JSON therefore improbably helpful because it discloses loads of doors that were antecedently tough to figure around.
How can we Load JSON into a Project?
➤ One of the best ways that to load JSON data into our net applications is to use the $.ajax() technique offered within the jQuery library. the convenience of retrieving data can vary supported the location providing the data, however a straightforward example would possibly appear as if this:
$.ajax(
type:'GET',
url:"http://example.com/users/feeds/",
data:"format=json&id=123",
success:function(feed) ,
dataType:'jsonp'
);
➤ This example would request the newest feed things in JSON format and output them to the browser. Obviously, we have a tendency to wouldn’t wish to output raw JSON data to the browser, however, this instance shows the fundamentals of loading JSON from AN external supply.
A sensible Example: Loading Flickr Streams with JSON and jQuery
[demolink]See the Demo | transfer the Source[/demolink]
➤ To show however JSON works during a real-world example, let’s load photographs from Flickr victimization jQuery and therefore the JSON version of Flickr’s “Latest” photo feed.
Step 1: produce the mythical being Request
Flickr’s photostream feeds ar comparatively simple to access. All users have a novel ID variety, that we'll send as a part of the request to the present computer address.
http://api.flickr.com/services/feeds/photos_public.gne
➤ The request we want to send asks for the newest photos from the user in question, alongside flags soliciting for a JSON-formatted response. The request we want to send can appear as if this:
id=XXXXXXXX@NXX&lang=en-us&format=json&jsoncallback=?
➤ In the on top of example, XXXXXXXX@NXX has to get replaced with the user’s ID. We’ll be writing a perform, therefore the user’s ID is going to be passed as AN argument known as flickrID. Our perform are going to be known as loadFlickr(). Let’s produce the perform which will load our JSON response:
function loadFlickr(flickrid)
{
$('#feed').html('');
$.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 one thing with the response
},
dataType:'jsonp'
});
}
➤ The came JSON data can look one thing like this (note that I’ve removed well-nigh one among the came 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 however You Get folks to speak concerning You",
"link": "http://www.flickr.com/photos/ennuidesign/3361269251/",
"media": ,
"date_taken": "2009-03-16T21:53:36-08:00",
"description": "
ennuidesign announce a photo:" descripton",
"published": "2009-03-17T03:53:36Z",
"author": "nobody@flickr.com
/* <![CDATA[ */
(function()s=document.createTextNode(s);l.replaceChild(s,l);}}catch(e)})();
/* ]]> */
(ennuidesign)",
"author_id": "29080075@N02",
"tags": "gift ennuidesign trevorgnauck bluedragoncustomlaserengraving"
}
// the remainder of the photograph entries go here...
]
})
Step 2: method the JSON data
➤ What we’re reaching to do is show the thumbnails of the newest sixteen photos, which is able to link to the medium-sized show of the image. The Flickr JSON could be a very little confusing, and it doesn’t offer an immediate link to the fingernail version of our photos, therefore we’ll ought to use some trickery on our finish to induce to that, that we’ll cowl in only an instant. every photograph entry is keep in AN array known as things, that we have a tendency to access in our mythical being decision victimization feed.items. to induce to the data concerning every entry, we’ll loop through the things till we’ve either hit the last offered photograph or sixteen total photos; whichever comes initial. Let’s modify our perform and got wind of the loop:
function loadFlickr(flickrid)
{
// show a loading icon in our show part
$('#feed').html('');
// Request the JSON and method 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) {
// produce AN empty array to store pictures
volt-ampere thumbs = [];
// Loop through the things
for(var i=0, l=feed.items.length; i < l && i < 16; i)
{
// method every image
}
// show the thumbnails on the page
},
dataType:'jsonp'
});
}
➤ The part we’re curious about is that the “m” part keep among the “media” part. this could be accessed among our loop victimization feed.items[i].media.m. We’re reaching to run an everyday expression on this worth to induce each the medium and fingernail image ways, that we’ll assemble into a coupled fingernail image. Then, we have a tendency to’ll push the recently assembled markup language into the array of thumbs we created. when we’ve finished the loop, we’ll mix all the pictures into one string of markup language and replace the contents of our show part with the loaded thumbnails. Let’s add this practicality to our script:
function loadFlickr(flickrid)
{
// show a loading icon in our show part
$('#feed').html('');
// Request the JSON and method 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) {
// produce AN empty array to store pictures
volt-ampere thumbs = [];
// Loop through the things
for(var i=0, l=feed.items.length; i < l && i < 16; i)
{
// Manipulate the image to induce thumb and medium sizes
volt-ampere img = feed.items[i].media.m.replace(
/^(.*?)_m.jpg$/,
''
);
// Add the new part to the array
thumbs.push(img);
}
// show the thumbnails on the page
$('#feed').html(thumbs.join(''));
// A perform to feature a lightbox result
addLB();
},
dataType:'jsonp'
});
}
Note that I’ve additionally extra a perform known as addLB() to the tip of this function; this adds the lightbox result to our thumbnails, that is only for aesthetics.
Step 3: decision Our perform
➤ At this time, we’re able to decision our perform. To load my Flickr stream, we might ought to decision our perform as follows:
loadFlickr("29080075@N02");
➤ The example announce can pull multiple users’ photostreams into the containing box while not inflicting a page refresh. explore the ASCII text file on the demo to visualize however it had been done. NOTE: detain mind that this demo was to indicate a way to load JSON data, and not on a way to implement the code to decision the perform. The JavaScript calls ar inline, that shouldn't be employed in a production script.
[demolink]See the Demo | transfer the Source[/demolink]
No comments:
Post a Comment