July 2, 2009 - 73 comments

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

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?

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:

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 family:

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 $.ajax() method results in the following JavaScript error:

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:

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.


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!

Published by: Jason Lengstorf in Development

  • 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.

  • dlv

    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!

  • dlv

    thanks Jason ! now it's more clear for me!

  • Jon

    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

    var feed = 'XXXXXXXX@NXX';

    $('.feed-link').bind('click', function(){ loadFlickr(feed); return false; });

    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:


  • Great article..

    very useful for me 🙂

    thx alot..

  • abu


  • @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.

  • Priyanka

    Thanks for making JSON easy to understand. It really helped me.

  • snoopy

    Hey Jason,

    Thanks you for this tutorial 🙂 it really helps .keep it up

    wish u loads of gud wishes

  • Mac

    Mmm – JQuery. The comments are almost as informative as the article. Thanks for taking the time to put this tutorial together.

  • Mac

    Mmm – JQuery. The comments are almost as informative as the article. Thanks for taking the time to put this tutorial together.

  • Mac

    Ahh! Sorry for the double post (although I have no idea how that happened.)

  • I have read your article , still I am confused what json is ? I google it and found that it make easy to interchange information and can be used over xml … well structured , but if I dont use it then wht happened ? what is it purpose ?

    I have used this function for username availability check :

    function ShowAvailability() {


    type: “POST”,

    url: “CS.aspx/CheckUserName”,

    data: '{userName: “' + $(“#”)[0].value + '” }',

    contentType: “application/json; charset=utf-8”,

    dataType: “json”,

    success: OnSuccess,

    failure: function(response) {





    what if I removed dataType: “json” from this $.ajax method . then what happened?

  • @anasanjaria:

    JSON is nothing more than a data interchange format. If you take the dataType: “jason” out of the function above, then the function wouldn't know what type of data to expect. I can't remember off the top of my head if jQuery uses a “best-guess” approach for unknown data types, so it may break your function.

    JSON is there to make it easy to trade data between pages/apps/scripting languages. You don't have to use it, but in my opinion it's faster and easier than using XML.

  • I have read article in which its written that :

    You see, in an Ajax environment where we make calls to web services we expect to get some data back in some form. Well, if we receive XML back as a direct result of an Ajax call, we have to send that data through an XML parser before we can even begin to manipulate the data to be useful to JavaScript. If we receive the data in JSON…we don't have to do anything but assign the results to a variable because JSON is already JavaScript. From there, we can manipulate the data as normal.

    can u provide me example by providing simple code which will illustrate above statement ?


  • @anasanjaria:

    Handling JSON was demonstrated in the above article. In an AJAX call, your success callback is set up with one argument (function(data){ /* do stuff */ }); inside that function you don't have to parse the data before outputting it. You can simply do something like this:

    // snipped for brevity

    “success” : function(data){



    // AJAX call continues here…

    To see how XML is parsed, check this link: http://www.w3schools.com/Xml/xml_dom.asp

    Good luck!

  • I am still confused .. I have understand the purpose of jason .. but if lets suppose use xml in ajax calll , no doubt it slows down the process … , but to clear my concept I am asking , after parsing xml how can I used that in javascript .. I want to clear this statement

    Well, if we receive XML back as a direct result of an Ajax call, we have to send that data through an XML parser before we can even begin to manipulate the data to be useful to JavaScript



  • The link I posted in my last comment shows the JavaScript used to parse and output XML data.

  • ABC

    I don't know anything about JSON but i have used jquery.. can i use josn like jquery? is it free waer? how to impliment it?

  • @ABC:

    No offense intended here, but did you actually read the article? What JSON is and how to use it is covered.

  • ABC

    No.. I am not.. Can u please provide me the tutorial for JSON?

  • It's good to learn about JSON here in this tutorial. Thanks.

  • If you like JSON you should really check out the entity format. Its faster/smaller in size and more secure than JSON. check it out at http://www.entity-format.co.uk

  • Kaspar Nikko

    Looks great nathan. thinking of switching my open source j2me app over to entity sending less data will definetly help improve my application. I also spotted that entity can convert JSON text over to ENTITY with a built in library call.

  • i actually came accross the entity format some months ago whilst reading FFDM it seems like a great format and is gaining alot of support, this is the article: http://flashflex.com/entity-data-interchange-evolved/

  • raymond trangia

    who is json nyahaha,that's a cool site ,can i name json script plugins to vonrod/?if that's impossible?

  • @raymond trangia

    I'm not sure I understand the question…

  • raymond trangia

    let's just say that json is the name of the javascript.And i was hoping of implementing json functionality same as the concept of a json but rename it into vonrod plugins..is that possible or idea's not fit to the ideals of the script itself?

  • Laurentiu

    yes, this wa exactly what i was looking for. thanks

  • @raymond trangia:

    I'm still not quite sure I understand the question. However, JSON is just a data interchange format. You can use it in any JavaScript files, no matter for what system they're written.

    Does that answer your question?

  • raymond trangia

    ah now i see clearly,Thanks for the great response and by the way your site is the coolest …. m/ rock on……m/


  • akanksha

    Excellent Writeup!!

  • jogesh_p

    lot of thanks to clear JSON concept,

    i really need this >>

  • iti tyagi

    what is the purpose of odata then?

    why odata takes json format?

  • maya

    hi, great tutorial.. have been having a hard time finding good json tuts out there… in this code…





    success:function(feed) {





    what is “feed”?? it has not been declared/init'd anywhere (that I can see…;-)

    thank you very much…

  • maya

    I just downloaded yr code..

    this line..


    this is how it is in yr code (in index.php):


    why is this

  • maya

    oh brother why doesn't it print right..

    in yr code, instead of


    is this:

    $(& # 39; # feed & # 39;).html

    added spaces to show you.. I think you get the drift…. why is your code written like this (or if it's not written like this, why does it transfer like this??)

  • maya

    var people = ([{

    why is this array wrapped in parenthesis?

    thank you…

  • Pingback: A Non-Programmer’s Introduction to JSON - blog.scottlowe.org - The weblog of an IT pro specializing in virtualization, storage, and servers()

  • Pingback: A Short Introduction to a Small Database | decipher()

  • Pingback: LLB Web App Series Part 1: Bower - Life-Life Balance()

  • Pingback: Idiot Learns to Code Vol III: 5 Things Codecademy doesn’t teach you about Javascript | Frank Merchlewitz()

  • Pingback: Idiot Learns to Code: 5 Javascript things Codecademy doesn't teach you - Silicon Prairie News()

  • Pingback: PHP Interview Question and answers Part2 | Sathya's Log()

  • Pingback: Don’t Use W3Schools.com To Learn HTML and JavaScript. | Grayson Peddie()

  • Pingback: new york story | Voyeur: Photos of Her()

  • Pingback: JSON: What It Is, How It Works, & How to Use It | skpachauri()

  • Pingback: Idiot Learns to Code: 5 Javascript things Codecademy doesn't teach you - Silicon Prairie News()

  • Pingback: Why is that So…Sticky? | Writing on the Web()

  • Pingback: Researching JSON | Bethany Larsen Graphics()

  • Pingback: JASON usage in applications()

  • Pingback: The File Manager, All its Features and Altering the User Settings | CSD 2550 Blog - Jean Gatt()

  • Pingback: Dejar de abrazar información | desdelapecerablog()

  • Pingback: Save and display score JSON | 我爱源码网()

  • Pingback: Use PHP to create RESTful API with auth | Star Dot Hosting()

  • Pingback: Use PHP to create RESTful API with auth()

  • Pingback: JSON: What It Is, How It Works, & How to Use It | ALL Internet()

  • Pingback: WebDev Blog #16 – Riot API | CSD2550 Blog - Steve Farrugia()