Sunday, November 9, 2008

What is JSON format?

JSON short for JavaScript Object Notation is a lightweight data interchange format.This is something that simple for humans to read as well as easy for machines to parse through.If you would like an even more detailed information about JSON please visit http://www.json.org/.


A JSON object is an unordered container of name/value pairs something similar to an object literal.The key/value pairs are seperated by a semicolon(:) while the values pairs are seperated by a comma. A name can be any string. A value can be any JSON value.,which are STRINGS,NUMBERS,ARRAYS,OBJECTS,BOOLEAN and NULL. The beauty of such a simple structure is that it can be nested easily but please do note that the effectiveness of a JSON object is best acheived when it is flat.

Example : 
{
"name" : "Sudheer",
"blog1" : "techno-helper",
"blog2" : "booksnme"
}


The JSON String is on the other hand an ordered container which has zero or more unicode characters wrapped in double quotes an using backslashes.This is similar to the String literals in 'JAVA' or 'C'

Example : 
{
"name" : "Sudheer",
"mesage" : "\"Run\" I shouted at her",
"big-message" : "You can also write
these
in lines"
}


JSON numbers are like the numbers in Java or JavaScript and can be an integer, real, or scientific excluding octal and hexa format numbers, also a leading zero is also not accepted.

Example:
{
"day" : 9,
"month" : 11,
"year" : 2008
}


JSON array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

Example:
[
{"name" : "Sudheer","blog1" : "techno-helper","blog2" : "booksnme"},
{"day" : 9,"month" : 11,"year" : 2008},
{"programmer":"true"},
{"null",null}
]

All about Javascript Objects

If you are a person who deals with anything to do with web pages then at some point of time you must have faced with the decision [or rather the requirement forced upon] to have to work with JavaScript, and subsequently objects in JavaScript. In this particular post I will be dealing with all that is needed about JavaScript objects.


An object like in any other programming language is a container of different properties having a name and a corresponding value to it. When speaking about javascript except the simple types,. i.e numbers, strings, booleans (true and false), null, and undefined; all other are considered objects.Another point worth mentioning here is the fact that objects in javascript are classless and are used for the simple fact collecting and organizing data and an object's property can be another object also.Also there is the prototype linkage feature that allows one object to inherit the properties of another.


So now that we are done with the basic requirement of explaining what objects are how can we go about creating one?Simple put a few name/value pairs surrounded by curly braces.This is a sort of crude way but the most direct method and one which you will be using in reality w.r.t objects.

// It is accepted if you do not give any name/value pairs
var emptyObject = {};

var customObject = {
"book-name" : "some book you like",
"author" : "the person who wrote it",
"first publish" : 2008
};
var complexObject = {
"string1" : "value1",
"string2" : "value2",
"" : "empty",
0 : 0,
"customObject" : customObject,
"newObject" : {
"key1" : "value1",
"key2" : "value2",
"key3" : "value3"
},
"newComplexObject" : {
"Obj1" : customObject["book-name"],
"Obj2" : customObject["author"]
}
};


Now the example above must have made it clear to you as to how are custom objects created [or like I felt the first time I saw something similar.... what the bloody hell is all this ;)] in general.Now there are few things that I would like to draw your attention to in the above set of examples and they would be:

  1. The key part will always be encased in quotes eg:"book-name" while it is optional for the value which can be encased if you want a string or a valid varible can be used eg: "customObject" : customObject.
  2. The key part or the value part can be empty while only the value can be a null
  3. You can use numbers for both key and value.
  4. A key, value or even the object can be empty.


Now that we have created some objects (quite a few many in my opinion) how are we to work on these say how do I get the date we so carefuly stored in these objects or how do we change the values or add new key value pairs etc; then let me point your attention again to the same example above only this time look at

"Obj1" : customObject["book-name"],
"Obj2" : customObject["author"]


This is how you access the data in the objects. So that means I just nee to call it with key (wonderful isn't it);then what happens if I cal with a key that is not existing say emptyObject["key"], this will be returning you a 'undefined' value.You would also be making calls like

complexObject.newObject.key1
customObject.author
// setting a default value
complexObject.newComplexObject.Obj3 || emptyObject
complexObject.string3 //undefined
complexObject.string3.subStr1 // TypeError Exception
// Avoiding TypeError Exception
complexObject.string3 && complexObject.string3.subStr1


Updating data :
Now that we are able to access data we will be updating data in the following manner

customObject.author = "So I got him wrong then";
complexObject.string3 = "value3";

Take note that when we are updating the value for a property there are two possibilities
  1. If the property exists its value will be update and
  2. If the property is non-existent then the object is augmented.


Objects as I said earlier are containers of data so we can never copy a object but we can only reference them so then

var x = customObject;
x.author="new author";
alert(customObject.author);
The above bock of code on execution will result in an alert message as "new author" rather than "the person who wrote it".


But then does that not seem a waste if you can just reference an an object and not make a copy of it., fortunately there is a way provided to solve this with the use of "prototype object".All the objects created from literals are linked to a default object provided with javascript Object.prototype


When making a new object select the object that should be its prototype by adding a beget method to the Object function. The beget method creates a new object that uses an old object as its prototype.

if (typeof Object.beget !== 'function') {
Object.beget = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
var newCustomObject = Object.beget(customObject);

The object so got has no effect on updating i.e. when we make changes to the object its prototype is unaltered.The 'typeof' is another useful tool provided to us for determining the type of the value stored in that particular property.Another useful method id the hasOwnProperty method, which returns true if the object has a particular property
newCustomObject.hasOwnProperty('number') // true
newCustomObject.hasOwnProperty('function') // false
complexObject.hasOwnProperty('object') // true


Deleting data :
The delete operator can be used to remove a property from an object if it has one.This gives us an interesting phenomenon

newCustomObject.author = "Again changing";
// now if we remove the author using delete
// the prototype value is restored
delete newCustomObject.author;

Sunday, September 14, 2008

The "for loop"

The for is a very versatile and powerful construct.The general format of the for statement

for(initialization;terminating condition;iteration){
// some code block
}

like all other statements if there is only one statement being repeated you can also avoid the curly braces.This structure is the one that java started with, but in jdk1.5 this has been extended further.Before going there I will first briefly describe about this because although the for loop is extended this format still remains to be quite popular.Let us start with each component of the loop statement:

initialization : This will typically contain the control variable(s) which will be acting as a counter to the loop we want.This is executed first by the compiler hence the control variables are also generally initialized at this point to limit their scope to the loop only.
Terminating condition :
This is executed next and contains or rather sets at which point the loop must be exited. The condition on evaluation should return a boolean value to simply state weather the loop should proceed for another round or exit.
Iteration : At this point we will be altering(altering may be incrementing or decrementing or both) the control variable(s).This will occur after the loop has been executed once after the terminating condition has returned a true and there is no force exit in the loop.

Each block except the termination condition may consist of a single or multiple comma(,) separated statements.For example :

for(int i=0,j=13;i==j;i++,j--){
// some code block
}

is a valid for implementation while the following is an invalid statement and results in a compile time error

for(int i=0,j=0;i<3,j<3;i++,j++){
// some code block
}

Although I mentioned during the description of each of the individual components in the 'for loop' the need for each to act w.r.t the loop process is not strictly necessary i.e. the following are all valid examples of 'for' implementation as the components in a for loop are completely independent of each other

for( ; ; ){
// some code block
}

for(int a=0;b<7;a++){
b=a-2;
}

for( ;a<10; ){
// this is a for loop which acts like a while
}

From jdk1.5 though the for loop has been extended to cater to the needs of the arrays and collection objects. For which the syntax has been modified to accept only two instead of three components.The generalized form of the extended for loop for arrays is


for(declaration : expression){
// some code
}


The declaration should be a newly declared block variable that is compatible with the elements of the array that you will be accessing while the expression must evaluate to the array you will be looping through.The following examples should help

class test
{
public static void main(String[] args)
{
String sArray[] = {"hello","world"};
int towDiArray[][] = {{1,2,3}, {4,5,6}, {7,8,9}};
Long LArray[] = {4L, 5L, 6L};
//Legal extended array usages
for(String s : sArray){
System.out.println(s);
}
for(long l1 : getlongArray());
for(long l1 : LArray);
for(int n[] : towDiArray);
for(int n : towDiArray[2]);
}

public static long[] getlongArray(){
long lArray[] = {11L, 12L, 13L};
return lArray;
}
}

The expression can be a array variable or a function that returns an instance of the array and the arrays are not restricted to the predefined but also customized ones can be used.The declaration though cannot be a variable that is already defined but one that is freshly declared i.e.

int i;
int intArray[] = {1,2,3,4,5};
for(i : intArray);

throws and exception like

test.java:6: not a statement
for(i : intArray[2]);
^
test.java:6: ';' expected
for(i : intArray[2]);
^
test.java:7: illegal start of expression
}

Regarding the usage of the extended for loop for collections I will be dealing with it in the next post

Saturday, September 13, 2008

Dragging a html element with javascript


<HTML>
<HEAD>
<TITLE> Drag n Drop </TITLE>

<style>

.dragme{
position:relative;
border:2px solid #FFFFFF;
width:75px;
font-weight: bold;
font-size:16px;
}

</style>

The style .dragme creates a container around the element which we would like to set as a movable entity in our page except for the position attribute the remaining all are optional and have been added to enhace the visual impact

<script language="JavaScript1.2">
var isIE=document.all;
var isNetscape=document.getElementById&&!document.all;

the above two variable are defined to decide which browser we are working on because the way page elements are accessed differs from IE and Netscape style browsers, both the variable above return an object if it is true else return false.
Eg : if you are in a isIE browser the 'isIE' equals an object and isNetscape is false.

var isdrag=false;
var x,y;
var dragObj;

onMouseMove(Event e) is called when the mouse moves. In order to enable dragging we set a isDrag variable which is set as true when mouse is pressed an reset when it is released.

function onMoveMouse(e)
{
if (isdrag)
{
dragObj.style.left = isNetscape ? tx + e.clientX - x : tx + event.clientX - x;
dragObj.style.top = isNetscape ? ty + e.clientY - y : ty + event.clientY - y;
return false;
}
}

function onMouseDown(e)
{
var dragObj = isNetscape ? e.target : event.srcElement;
var topelement = isNetscape ? "HTML" : "BODY";

while (dragObj.tagName != topelement && dragObj.className != "dragme")
{
dragObj = isNetscape ? dragObj.parentNode : dragObj.parentElement;
}

if (dragObj.className=="dragme")
{
isdrag = true;
dragObj = dragObj;
tx = parseInt(dragObj.style.left+0);
ty = parseInt(dragObj.style.top+0);
x = isNetscape ? e.clientX : event.clientX;
y = isNetscape ? e.clientY : event.clientY;
document.onmousemove=onMoveMouse;
return false;
}
}

document.onmousedown=onMouseDown;
document.onmouseup=new Function("isdrag=false");

</script>


</HEAD>

<BODY>
<div id="div1" class="dragme">Drag this </div>
</BODY>
</HTML>

Friday, September 12, 2008

The prologue

This is just something that I have wanted to be doing for quite sometime, you know especially when I am in search of some information or something that I did do sometime back or something really good with my job. I know most of you must have felt the same many times.... and the result of that is 'THIS'. Here I will be trying to get as much as I can (of course only technical) that will help us make our programming that bit better and that bit more beautiful.
I am also planning to request a few of my friends to write here so that I too get to know something I missed ;)