Sei sulla pagina 1di 11

Part 1 - Introduction to JSON123

Next

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 APIresponses, 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 2. 3. 4. 5. 6. 7. 8. 9. 10. } myObj = { name: 'Frank', age: 24, engaged: true, favorite_tv_shows: ['Lost', 'Dirty Jobs', 'Deadliest Catch', 'Man vs Wild'], family_members: [ {name: "Frank", age: 57, relation: "father"}, {name: "Tina", age: 26, relation: "sister"} ]

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. 12. var property = "age" 13. 14. 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

Next, I will demonstrate how JSON is commonly used in API calls.

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.js on
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 yourHTML as a javascript include file:
1. <script type="text/javascript" 2. src="http://twitter.com/statuses/user_timeline/franklakatos.json"> 3. </script>

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" 2. src="http://twitter.com/statuses/user_timeline/franklakatos.json?count=1"> 3. </script>

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_image s\/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\/them e1\/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, 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 variablemyTweets, 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.
1. <script type="text/javascript" 2. src="http://twitter.com/statuses/user_timeline/franklakatos.json?callback=cb&coun t=1"> 3. </script>

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. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 4. <head> 5. <title>Twitter API w\ JSON</title> 6. <script type="text/javascript"> 7. var myTweets 8. function cb(data){ 9. myTweets = data; 10. document.write(myTweets[0].user.name + " says:<br/>\"" + myTweets[0].text + "\""); 11. } 12. </script> 13. <script type="text/javascript" 14. src="http://twitter.com/statuses/user_timeline/franklakatos.json?callback=cb&coun t=1"> 15. </script> 16. </head> 17. <body> 18. </body> 19. </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."

Next, we will get into the true power of using JSON: implementing client and server communication.

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 usingjson_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. 9. $myJSONTweets = json_encode($myTweets); 10. 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. #} 15. ?>

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. 9. $myTwitterUser = array("name" => "franklakatos"); 10. $myTweets['user'] = $myTwitterUser; 11. $myJSONTweets = json_encode($myTweets); 12. 13. echo $myJSONTweets; 14. #{"text":"Just handed in my last project ever for my masters, all I have now is finals next week. Goodbye, school. Hello, life.", 15. #"created_at":"Thu May 07 21:36:12 +0000 2009", 16. #"user":"{"name":"franklakatos"}" 17. #} 18. ?>

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. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 4. <head> 5. <title>Twitter API w\ JSON</title> 6. <script type="text/javascript" src="http://www.google.com/jsapi"></script> 7. <script type="text/javascript"> 8. // Load jQuery 9. google.load("jquery", "1.3"); 10. </script> 11. <script type="text/javascript"> 12. $(function(){ 13. //Get the JSON string and pass it to the cb function 14. $.get("twitter.php", function(data){cb(data)}); 15. }) 16. 17. function cb(data){

18. //converts the JSON string to a JavaScript object 19. eval("myTweets="+data); 20. myTweets = dataToObj; 21. document.write(myTweets.user.name + " says:<br/>\"" + myTweets.text + "\""); 22. } 23. </script> 24. </head> 25. <body> 26. </body> 27. </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']);

2. Why use JSON? The answer is portability and structure. 3. JSON is portable because parsers and writers are available for many, many languages. This means that JSON that a PHP script generates can be very easily understood by a JavaScript script. It is the best way to transmit complex structures like arrays and objects, and have it still be compatible with multiple languages.

4. JSON provides structure because the data you transmit with it can have consistent formatting. This is instead of transmitting back plain-text (i.e. unformatted) data, like commaseparated or delimited data. 5. Data that is merely delimited (for example, "BookName1,BookName2,BookName3") is more difficult for humans to understand, debug, and work with. If you wanted to debug a response between your server and your browser and the data was delimited (like my example above), you might have a hard time understanding it. Also, if you want to add different data types, provide separate records, etc., then your custom data format becomes more complicated. Eventually, you might end up reinventing JSON. 6. As a side note, JSON is indeed better than XML. It is much more efficient space-wise. There are no tag names to take up space. Structure is created via nested braces, instead of verbose tags. 7. Resources 8. Here is an interesting article on the differences and pros/cons of XML and JSON:http://www.json.org/xml.html 9. Examples 10. Per your request, here is an example of encoding JSON with PHP. This is ripped from the docs: 11. $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); 12. Output: 13. {"a":1,"b":2,"c":3,"d":4,"e":5} 14. Contrast this to something like this, without JSON: 15. a,1 b,2 c,3 d,4 e,5 16. To parse that, you'd have to iterate through each line, split the values yourself, and then create the array. This isn't that difficult, but imagine you have a nested object: 17. $arr = array ('a'=> array(1,2,3),'b'=> array('a' => 1, 'b' => 2),'c'=>3,'d'=> array(1,2,3,4,5) ,'e'=>5); // etc. 18. With JSON, it's no different to encode it. Just use json_encode. But, encoding this manually, and then decoding it manually would be significantly more work.

Potrebbero piacerti anche