Mock tests, Interview questions, Tutorials and Tech news
 
 
Home > Programming / tutorials > JSON Javascript Tutorial

JSON Javascript Tutorial

January 27th, 2010 Leave a comment Go to comments

Introduction : Before we begin our journey of JSON, let’s write down a small piece of code .

<html>
<head>
<script language=”javascript”>
var objTest = {
“TestName” : “SCJP 5 Mock Test”,
“Description” : “This has questions for SCJP 5 mock test”,
“Rating” : 4
};
</script>
</head>
</html>

Our first reaction would be “Hey, wait. This is java script code. What is new in this?”. Welcome to the world of JSON.

Have we ever realized that these braces have huge potentials to store massive information under its hood. Here is JSON. JSON (Java Script Object Notation) provides a simple data format for the exchange of information between the browser and server. In other words JSON is light weight data-interchange format. Now you can see from above code that it has the potential to store any data type of information. We can store strings, integer, float, arrays, function or even other objects inside as per our requirement and JSON does not even bother about the type of data.

Objective

The main objective of this tutorial are :

(1)   Why JSON
(2)   Using JSON?
(3)   Accessing data in JSON
(4)   Get JSON via AJAX
(5)   JSON with other sever side scripts
(6)   Future of JSON

Why JSON

(1)   Because JSON is easy to write. It is just like creating and accessing class in javascript in object notation
(2)   If you like HashTables, you will fall in love with JSON.
(3)   JSON is just key : value pairs assigned within an object.
(4)   JSON is very fast.
(5)   It is easy to understand and can be integrated in any web application very easily.
(6)   Better organized data if prepared in well mannered way.

Using JSON and Accessing data in it

Let’s dig further our original example above. We created an object ‘objTest’ and stored some information. Yes, it is just like a class we use in other languages. So, how to access the data inside it?

<html>
<head>
<script language=”javascript”>
var objTest = {
“TestName” : “SCJP 5 Mock Test”,
“Description” : “This has questions for SCJP 5 mock test”,
“Rating” : 4
};
document.write(objTest.TestName);        // SCJP 5 Mock Test
document.write(objTest.Description);      // This has questions for SCJP 5 mock test
document.write(objTest.Rating);             // 4
</script>
</head>
</html>

As you can see from above example that we are getting the data by conventional attribute access mechanism [<object>.<attribute>]. So objTest.TestName will give the TestName’s value. JSON obeys your request and shows you the desired information. Please keep in mind that everything in javascript is an object, so values can be string, integer, float, array, function and as mentioned earlier can be other objects.

Let’s take a complex example to show the JSON capabilities :
<html>
<head>
<script language=”javascript”>
var objTest = { “certification” : [     // certification is an array in objTest.
{ "TestName" : "SCJP 5 mock Test",  // 1st element
"Description"  : "This has questions for SCJP 5 mock test.",
"Rating"       : 4 },
{ "TestName" : "SCJP 6 mock test",  // 2nd element
"Description"  : "This Test is for Sun Certified Programmer for the Java Platform.",
"Rating"       : 4.5 }
], // End of certification array.
“aptitude”       : [ // aptitude is second array in objTest.
{ "TestName" : "Aptitude test",  // 1st element
"Description"  : "This test is based on logical and basic arithmatical reasoning logic.",
"Rating"       : 4},
{  "TestName" : "Anaytical Ability",  // 2nd element
"Description"  : "This test is aimed at testing your Analytical Ability.",
"Rating"       : 5 }
] // End of aptitude Array.
} // End of objTest
document.writeln(”Test Name : ” + objTest.certification[0].TestName + ‘<br/> Test Description : ‘ + objTest.certification[0].Description + ‘<br/> Rating : ‘ + objTest.certification[0].Rating);
/*————————————————OUTPUT———————————————————–
Test Name : SCJP 5 mock test
Test Description : This Test is for Sun Certified Programmer for the Java Platform.
Rating : 4.5
———————————————————————————————————————*/
</script>
</head>
</html>

Let’s understand the above example. Here certification is an object that holds two JSON objects that shows the TestName, Description & Rating of 2 certification test. The same applies for aptitude. It also holds two JSON objects and shows TestName, Description & Rating of 2 aptitude test.

There is an another approach to access the JSON object values.

document.write(objTest["TestName"]);        // SCJP 5 Mock Test

Accessing JSON via AJAX

We have heard much about the AJAX and some of us are using it extensively in our daily development life. Here we will try to investigate how we can get the JSON from AJAX callback. In this method, we call the predefined function and passes the JSON data to the function as the first argument. This method is very popular while dealing with 3rd party JSON files.

<html>
<head>
<script>
function processJSONData(paramJSON)
{
document.writeln(paramJSON.TestName);   // TestName : SCJP 5 Mock Test
document.writeln(paramJSON.Description); // Description : This has questions for SCJP 5 mock test
document.writeln(paramJSON.Rating);        // Rating : 4
}
// User requests the service (hosted on same domain or another domain using AJAX) and
// we are sure that we get the results in JSON format only
// Received from the server
var JSONFile = “processJSONData({’TestName’ : ‘SCJP 5 Mock Test’, ‘Description’ : ‘This has questions for SCJP 5 mock test’, ‘Rating’ : 4})”;
eval(JSONFile);
</script>
</head>
</html>

The above example written in javascript. When this script is passed through the eval() method it parses the processJSONData method and shows the desired results.

json_samples (right click over the link and save as target)

JSON with other sever side scripts

Since JSON is java script object notation, so you can use it in your web application that can be in ASP.NET, PHP etc.

Future of JSON

Almost every browser is giving support for JSON and dozens of websites are coming everyday using JSON. Once you start using JSON, you will come to know its true power and what it can offer to a  developer.

Be Sociable, Share!
  1. shinesh
    December 7th, 2012 at 06:27 | #1

    IT’s cool, but describe second example more depth

    And it’s possible to fetch array element with name wihout number

    means
    objTest["TestName"]

    insetad of
    objTest[0]

    Thanks

  2. zaheer
    July 17th, 2012 at 01:12 | #2

    Hi,
    Can any one tell how to insert the textbox value in database using Jquery /json,
    i tried one example but its not working…..
    http://www.devtechie.com/post/2011/05/26/Insert-Data-using-JSON-ASPNET-Web-services-and-jQuery.aspx

  3. June 24th, 2012 at 23:44 | #3

    How to Insert data into database by using json

  4. Sun
    June 8th, 2012 at 06:58 | #4

    This was useful but,
    can anyhelp to retrive data from database and display in grid using ajax and json?

  5. August 5th, 2011 at 07:16 | #5

    I have put together a little JSON sample that iterates over a JavaScript object and posts the property values to a cross domain server that is hosts by a DotNet.aspx page that then converts a C# object to a JSON string that is then posted back to the browser and converted back to a JavaScript object without having to use Window.Eval()

    The resultant JavaScript object is then finally past back to a call-back function that is ready to uses and the code does not need 3rd party libraries, works in net framework 2.0 and upwards and has been tested with IE6-IE9, Firefox plus it’s lightweight.

    Click my name for full details

  6. May 31st, 2011 at 08:36 | #6

    Onyx, did you parsed the JSON results into your page ? If yes then you can store that in some hidden field or pass the value into form variables.
    Once you are able to parse JSON results, the manipulation of values is same as you would have done normally.

  7. May 30th, 2011 at 20:25 | #7

    Hi Vinay,
    Could you help me please, how to pupulate json result into form automatically?
    thank you for helping.

  8. Raheel
    February 22nd, 2011 at 02:50 | #8

    interesting and very useful script

  9. February 14th, 2011 at 11:55 | #9

    great….this is really useful…thanks for sharing….

  10. Raymond trangia
    February 3rd, 2011 at 03:36 | #10

    This is what i need to build a site.

    This site also have codes but it uses json with something curl

    http://linesforme.blogspot.com

  11. October 14th, 2010 at 09:17 | #11

    Thanks Renjith. Readers like you keep us motivated. :)

  12. Renjith Maxy
    October 14th, 2010 at 05:47 | #12

    Good Chunk of Information dude, keep posting.

  13. October 1st, 2010 at 07:22 | #13

    This website is cool.. Keep it Going

  14. September 30th, 2010 at 13:51 | #14

    @Moshe
    Did not used JSON with php so can’t help you out much there. Will try to answer your other question.

  15. September 30th, 2010 at 11:06 | #15

    Hello Vinay,
    Thanks for explaining the basics so clearly, you’re a good teacher! If you could go on further, would you outline the basic steps of how to send data with JSON from client to a server in a PHP application?

    I saw the JSON.org JSON Request page you linked to, but there is no example. Your examples are very helpful. (http://www.json.org/JSONRequest.html)

    The main points in question would be:
    *the client defines and populates JSON object with data. (this article explained this part well)

    *now, does the client use a FORM to send the JSON object? How wold the form send back the object, which is not form “inputs”? Does the client use a different method to return the JSON to the server? Is this where the JSONRequest comes in? Does a function simply activate JSONRequest? One clear example will be very helpful.

    *how does the PHP server ‘read’ or ‘decode’ the returned JSON so we can add the data to a database?

    *Sending data in the other direction, from server to client, seems simpler – the PHP would simply write the JSON and the data while preparing the page for the client. The client page then sees the JSON in the javascripts.

    Thanks!
    We’re working on the website for a company that is renting electric bicycles to commuters at the train station.

  16. August 13th, 2010 at 06:07 | #16

    Cool. Helpful. Interesting.

  17. August 13th, 2010 at 06:03 | #17

    Good stuff. Keep it going.

  18. June 24th, 2010 at 12:08 | #18

    Thank You Sarika. We appreciate the feedback and these comments keep us motivated to write more.

  19. Sarika
    June 24th, 2010 at 11:44 | #19

    Vinay,

    Your articles are very informative and substantiated with simplified examples. Looking forward for more articles from you.

  20. April 21st, 2010 at 20:59 | #20

    @Sreekar thanks for pointing out. I have updated the link. It works now.

  21. Sreekar
    April 21st, 2010 at 16:47 | #21

    Hi Vinay,
    Could you please update the json_samples2.htm file. Looks like the link is broken.

    Thanks!

  1. January 27th, 2010 at 07:33 | #1
  2. January 27th, 2010 at 09:27 | #2
  3. January 27th, 2010 at 10:31 | #3
  4. January 27th, 2010 at 23:02 | #4
  5. January 29th, 2010 at 10:41 | #5
  6. February 2nd, 2010 at 21:29 | #6
  7. February 12th, 2010 at 20:51 | #7
  8. March 30th, 2010 at 16:55 | #8
  9. May 2nd, 2010 at 22:04 | #9
  10. May 8th, 2010 at 14:23 | #10

Get Adobe Flash playerPlugin by wpburn.com wordpress themes