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;