Introduction to JSON


What is JSON?

JSON, or JavaScript Object Notation, has been getting a large amount of attention recently in the IT world. This is mostly powered by its extremely lightweight implementation, its common usage in API responses, and its already native support in JavaScript. JSON isn’t simply a way to code objects in JavaScript, but it is the actual form that a JavaScript engine will map the object to in memory. In short, it is an extremely fast and powerful way of transporting data between two interfaces.

How does it work?

JSON is capable of setting up data constructs for integers, strings, arrays, and booleans – the most essential data building blocks. Using a carefully defined syntactical construct, JSON can be used to outline an object and with the use of javascript’s eval() function, they can be converted to a working object.

But the power does not end there. Other popular programming languages have been implementing native support for JSON, such as PHP and ActionScript. For example, PHP can now convert an associative array of data into a JSON string by using the new json_encode() function, provided in version 5.2+ of the language. For languages without native support, you can find a full range of implementation classes available at the JSON website.

The Syntax: explained

Declaration

All JSON objects are declared with a pair of curly braces. You can assign them to a variable like you would any other data structure.

  1. var myObj = {}

That’s it! While not very powerful, this is all that’s required to create objects using JSON. So let’s start adding some properties to this object.

Strings

We are going make this object represent me, so let’s start by adding my name.

  1. var myObj = {name: ‘Frank’}

Let’s take a second to carefully look at what we did here. We wanted to add a property called “name”, and to do so, you simply write the property, “name”. We follow the property label by a colon to separate the property name and its value. To the right of the colon, comes the value. Since we wanted the value to be a string, we put it in quotes.

With the JSON we have put in place, you are now able to access the property by using the dot notation. To access a property, follow the “Variable [dot] property” construct.

  1. alert(myObj.name) // “Frank”

Integers

If we wanted to assign a property to the object of an integer data type, there is no need to quote the value.

  1. var myObj = {age: 24}

Multiple properties are separated by a comma.

  1. var myObj = {name: ‘Frank’, age: 24}
  2. alert(“My name is ” + myObj.name + ” and I’m ” + myObj.age);
  3. // “My name is Frank and I’m 24

Booleans

Like integers, booleans are also unquoted

  1. var myObj = {name: ‘Frank’, age: 24, engaged: true}

Arrays

Arrays can contain a collection of the previously mentioned data types. To define an array, wrap the value in square brackets and separate the values with commas.

Note: I will now add line breaks and indentation for legibility. It has no bearing on the working order of the object.

  1. var myObj = {
  2. name: ‘Frank’,
  3. age: 24,
  4. engaged: true,
  5. favorite_tv_shows: [‘Lost’, ‘Dirty Jobs’, ‘Deadliest Catch’, ‘Man vs Wild’]
  6. }

You can access a value in an array in the object by using a combination of the dot notation (to access the objects property) and index notation (to access an indexed value of an array).

  1. alert(myObj.favorite_tv_shows[1]); // “Dirty Jobs”

To take the array complexity one step further, an array can also contain other objects.

  1. var myObj = {
  2. name: ‘Frank’,
  3. age: 24,
  4. engaged: true,
  5. favorite_tv_shows: [‘Lost’, ‘Dirty Jobs’, ‘Deadliest Catch’, ‘Man vs Wild’],
  6. family_members: [
  7. {name: “Frank”, age: 57, relation: “father”},
  8. {name: “Tina”, age: 26, relation: “sister”}
  9. ]
  10. }

This still requires dot and index notation, with an additional dot notation for accessing the property of the object found in the indexed array value.

  1. alert(myObj.family_members[1].name) // “Tina”

There is one situation where you will use square brackets to access an objects property and not the dot notation: when you are using a variable as the property name. For example:

  1. var myObj = {
  2. name: ‘Frank’,
  3. age: 24,
  4. engaged: true,
  5. favorite_tv_shows: [‘Lost’, ‘Dirty Jobs’, ‘Deadliest Catch’, ‘Man vs Wild’],
  6. family_members: [
  7. {name: “Frank”, age: 57, relation: “father”},
  8. {name: “Tina”, age: 26, relation: “sister”}
  9. ]
  10. }
  11. var property = “age”
  12. alert(myObj[property]); // “24”

Recap

Take some time experimenting with JSON and you will see that you can pick up the concept and syntax rather quickly. As a caveat that may save you time in the future: certain languages require you to quote the property names, such as ActionScript. If not, it will complain.

  1. myObj = {name: “Frank”} // will complain
  2. myObj = {“name”: “Frank”} // will work

Loading External JSON into your Application

For our example, we are going to use the Twitter API. For those of you who haven’t tried to interface with Twitter, it is extremely easy to comprehend. Let’s say that you absolutely adore me. So much, in fact, that you would love to put my latest tweets on your very own web site. Bless your heart.

Step 1 – Get the Object

If you look over the Twitter API, you can read over all of the wonderful method calls they provide for you, including one that lets you retrieve a user’s timeline in JSON format. The format of the URI is as follows:

http://twitter.com/statuses/user_timeline/franklakatos.json

If you try to load this URI in your browser, it will prompt you to download a file. Why a file, and what is inside of it? Since JSON is a front-end technology, it would violate Cross-Site Scripting (XSS) rules to make calls to another domain using the XMLHttpRequest object, the object that powers other asynchronous calls as with AJAX. To work around doing this, you will include this file call in your HTML as a javascript include file:

The API request commonly makes available a varying number of parameters to control the output of your request, such as a limit to how many to return.

  1. <script type=”text/javascript”

If you make a call to this JSON file, you will be returned a file that contains an object that looks like this:

  1. [{
  2. “text”:”Just handed in my last project ever for my masters, all I have now is finals next week. Goodbye, school. Hello, life.”,
  3. “in_reply_to_screen_name”:null,
  4. “user”:{
  5. “profile_background_color”:”9ae4e8″,
  6. “followers_count”:10,
  7. “profile_image_url”:”http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/110871907\/me_copy_normal.jpg”,
  8. “description”:null,
  9. “utc_offset”:null,
  10. “friends_count”:6,
  11. “profile_text_color”:”000000″,
  12. “screen_name”:”franklakatos”,
  13. “following”:null,
  14. “profile_background_image_url”:”http:\/\/static.twitter.com\/images\/themes\/theme1\/bg.gif”,
  15. “profile_link_color”:”0000ff”,
  16. “url”:null,
  17. “name”:”franklakatos”,
  18. “favourites_count”:0,
  19. “protected”:false,
  20. “profile_sidebar_fill_color”:”e0ff92″,
  21. “time_zone”:null,
  22. “profile_sidebar_border_color”:”87bc44″,
  23. “profile_background_tile”:false,
  24. “location”:null,
  25. “id”:18163247,
  26. “notifications”:null,
  27. “statuses_count”:67,
  28. “created_at”:”Tue Dec 16 14:44:59 +0000 2008″
  29. },
  30. “truncated”:false,
  31. “in_reply_to_status_id”:null,
  32. “in_reply_to_user_id”:null,
  33. “id”:1731244194 begin_of_the_skype_highlighting              1731244194      end_of_the_skype_highlighting,
  34. “favorited”:false,
  35. “source”:”<a href=\”http:\/\/twitterfon.net\/\”>TwitterFon<\/a>”,
  36. “created_at”:”Thu May 07 21:36:12 +0000 2009″
  37. }]

Look at all that great content! A quick glance will show that the object is an array of objects (notice the string begins and ends with square brackets). Therefore, if we assigned this string to a variable myTweets, we can access our first object with myTweets[0], for instance.

Here are some examples of accessing the data:

  1. myTweets[0].text // “Just handed in my last project ever for …”
  2. myTweets[0].created_at // “Thu May 07 21:36:12 +0000 2009”
  3. myTweets[0].user.name // “franklakatos”

Step 2 – Access the Data Using Callbacks

The astute reader may have noticed that the object included in the API file has no variable assigned to it, and since we include the JSON object in an external javascript file, there is no way for us to assign one to it. So how are we suppose to access this data?

The answer, callbacks. Most APIs using JSON will implement a callback system, where you tell it a name of one of your functions and when your site is done downloading the JSON file, it will automatically call that function and pass the object as an argument.

Inside your function, you can assign it to a variable, use the data as needed, et cetera. All you need to do is create the function with one parameter, which will be used to pass the object along.

  1. var myTweets;
  2. function cb(data){
  3. myTweets = data;
  4. }

Now you can access the objects data whenever you would like, using the myTweets global variable. Here is an example of how you can implement the Twitter API to use in production:

  1. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
  2. <html xmlns=”http://www.w3.org/1999/xhtml&#8221; xml:lang=”en” lang=”en”>
  3. <title>Twitter API w\ JSON</title>
  4. <script type=”text/javascript”>
  5. var myTweets
  6. function cb(data){
  7. myTweets = data;
  8. document.write(myTweets[0].user.name + ” says:<br/>\”” + myTweets[0].text + “\””);
  9. }
  10. <script type=”text/javascript”
  11. </head>
  12. </body>
  13. </html>

…which would output..

  1. franklakatos says:
  2. “Just handed in my last project ever for my masters, all I have now is finals next week. Goodbye, school. Hello, life.”

Client / Server Data Retrieval With JSON

Now that you are well versed with the concepts and syntax of JSON, and you have a working example of how to use JSON for client-side API communication, let’s see how we can take advantage of server-side technologies to transfer data between the client and the server.

Until recently, the world of asynchronous communication was ruled by XML. While in production successfully, XML is still an extremely bulky language, increasing data transfer overhead. Perhaps its biggest downfall, however, is that XML is commonly generated by server languages who many times do not have an XML converter, requiring manual conversion. Then, they are delivered to client languages, most notably JavaScript, who also do not have native support for XML. It would make more sense, for code simplicity and maintenance, for everyone to speak the same language.

Using PHP with JSON

Mentioned earlier, as of PHP 5.2, there is native support for encoding and decoding JSON using json_encode() and json_decode(), respectively. That means that you can now create JSON strings in PHP files, allow JavaScript to make calls to the file, have JavaScript manipulate the object and send it back to PHP, all in the same notation!

Getting Started

We are going to create a PHP file that will output JSON in the same manner as the Twitter API call. Since the PHP file will be hosted on the same domain as the HTML file, we can then make an asynchronous request to the object to load to the page.

If you stop and think about the difference between and JSON and a PHP associative array, you will notice they are extremely similar: they both represent the same data types in the same manner, and they both have a specific syntax for doing so. Therefore, to create a JSON object in PHP, you will simply create an associative array in the same manner as usual. When you are finished creating the array, you will pass the array into the json_encode() function, and it will take care of updating the syntax.

  1. <?php
  2. $myTweets = array(
  3. “text” => “Just handed in my last project ever “.
  4. “for my masters, all I have now is finals “.
  5. “next week. Goodbye, school. Hello, life.”,
  6. “created_at” => “Thu May 07 21:36:12 +0000 2009”
  7. );
  8. $myJSONTweets = json_encode($myTweets);
  9. echo $myJSONTweets;
  10. #{“text”:”Just handed in my last project ever for my masters, all I have now is finals next week. Goodbye, school. Hello, life.”,
  11. #”created_at”:”Thu May 07 21:36:12 +0000 2009″
  12. #}
  13. ?>

The only other data type to account for is including object in an associative array, but this is also trivial. Simply create another associative array and add it as a value to the main associative array.

  1. <?php
  2. $myTweets = array(
  3. “text” => “Just handed in my last project ever “.
  4. “for my masters, all I have now is finals “.
  5. “next week. Goodbye, school. Hello, life.”,
  6. “created_at” => “Thu May 07 21:36:12 +0000 2009”
  7. );
  8. $myTwitterUser = array(“name” => “franklakatos”);
  9. $myTweets[‘user’] = $myTwitterUser;
  10. $myJSONTweets = json_encode($myTweets);
  11. echo $myJSONTweets;
  12. #{“text”:”Just handed in my last project ever for my masters, all I have now is finals next week. Goodbye, school. Hello, life.”,
  13. #”created_at”:”Thu May 07 21:36:12 +0000 2009″,
  14. #”user”:”{“name”:”franklakatos”}”
  15. #}
  16. ?>

The JavaScript Call

In similar fashion as before, we need to have JavaScript access an external file to get a JSON object. While before we embedded a script tag to avoid the limitation of same-domain access with the XMLHttpRequest object, we can now take advantage of the asynchronous call as we are hosting the PHP file.

Note: I will be using jQuery to help us out with the XMLHttpdRequest

  1. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
  2. <html xmlns=”http://www.w3.org/1999/xhtml&#8221; xml:lang=”en” lang=”en”>
  3. <title>Twitter API w\ JSON</title>
  4. <script type=”text/javascript” src=”http://www.google.com/jsapi”></script>
  5. <script type=”text/javascript”>
  6. // Load jQuery
  7. google.load(“jquery”, “1.3”);
  8. <script type=”text/javascript”>
  9. $(function(){
  10. //Get the JSON string and pass it to the cb function
  11. $.get(“twitter.php”, function(data){cb(data)});
  12. })
  13. function cb(data){
  14. //converts the JSON string to a JavaScript object
  15. eval(“myTweets=”+data);
  16. myTweets = dataToObj;
  17. document.write(myTweets.user.name + ” says:<br/>\”” + myTweets.text + “\””);
  18. }
  19. </head>
  20. </body>
  21. </html>

Perhaps the most confusing part of all of this is the use of the eval() function. The eval function takes a string and executes it like it is code. When we receive JSON from PHP, it is simply a string that is notated as a JavaScript object, but it is not yet a JavaScript object. It is up to JavaScript to take this string and covert it to an object. That is what eval() is used for, and as you can see we assigned it to the variable name myTweets.

Going Back to the Server

So let’s say you have a system in place that allows you to update the text property and PHP will update Twitter accordingly. That means we can update the object that PHP originally provided us with, update the values of some properties, and send it back to PHP.

  1. myTweets.text = “My New Text”

When you finish with updates such as the former, you can then serialize the object back into a JSON string and send it in a POST request back to PHP. There are many jquery plugins to do this, or if you prefer a little lower level, JSON.org offers a parser for the converting.

  1. //implements the JSON.org parser
  2. mySerializedTweets = JSON.stringify(myTweets);
  3. $.post(“twitter.php”,{page: submit, obj: mySerializedTweets});

Now, PHP can receive the JSON string and convert it back into the associative array you started with.

  1. $myTweets = json_decode($_POST[‘obj’]);
Advertisements
By karuppasamy11486 Posted in Uncategorized

One comment on “Introduction to JSON

  1. Pingback: It Box @ All Around the World News

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s