Monday, November 3, 2014

How do you work with Javascript Object Notation?

With enhancements to JavaScript in recent years and the advent of AJAX, interest in JavaScript took a turn for the better. Early on with AJAX it was recognized that there was a contender for XML for handling data which was stable, faster, and portable. This was the beginning of JSON.

Although RFC 4627 marks a JSON milestone, it appears that it had already been discussed among the JavaScript cognoscenti. JSON is equally, or even more suited, for data exchange than XML, which was originally considered to be the ideal wire friendly format.
What is JSON?
So what is JSON? It’s an acronym you might have started appearing in greater frequency on the Internet. JSON stands for JavaScript Object Notation. Well, it is a special object notational construct and is a subset of JavaScript. It can be used wherever JavaScript can be used and you do not need to download anything. There is no need to worry about the version of JavaScript.
You can read more about JSON in RFC 4627. JSON was designed to be minimal (small), textual, and portable. The MIME Media Type is now registered as application/json. JSON can handle exchanging data in applications written in different programming languages such as C, C#, ColdFusion, Perl, Python, Ruby, and so forth.

JSON Basics
JSON has simple types and two structures which are very similar to the universally used data structures such as dictionary objects, hash values, key/value pairs, lists, sequences, record sets, arrays and so on. It is a natural.

Types in JSON

JSON’s JavaScript subset admits of the following four primitive types.
* strings [except ", and Control Characters]
* number [Integer, real and Floating point]
* Boolean [literals, true and false]
* null

Unlike JavaScript it does not support hexadecimal and octal representation of numbers, nor does it support NaN (not a number) and infinity. Also numbers do not need quotes but strings do.
In addition to the four primitives it also supports two kinds of structures, object and array.

JSON Object
A JSON object is an unordered set (members) of key/value pairs, with keys being separated by values using a colon (:) and the members being separated by a comma (,). The colon and the comma are respectively called the name separator and the value separator.
Here is a variable that represents a JSON object with three members. “company”:”Hodentek” is one member of the JSON object where the key, which is “company,” is separated by the value, which is “Hodentek.” The object is always enclosed between curly brackets as shown in the declared variable. In this example all the values are of type string.

var jObj={"company":"Hodentek", "phone":"609-275-1205", "city":
"Plainsboro"};

You can access any member’s value using the dot notation as shown in the next snippet, which shows the “phone” of the object in the alert as “609-275-1205.”

alert(jObj.phone);//

The values of members of the JSON object can be of different types as shown in the following code listing.
 
Script Language="JavaScript"›

//values are numbers (integer and floating point)
var jobj2={"sunday":1, "tuesday":2.85, "wednesday":3};
document.write("‹b›jobj2.tuesday:‹/b› " + jobj2.tuesday +"‹br›");
//values are of mixed types
var jObj3={"culprit":true, "innocent":false, "notsure":null};
document.write("‹b›jObj3.culprit:‹/b› " + jObj3.culprit +"‹br›");
document.write("‹b›jObj3.innocent:‹/b› " + jObj3.innocent +"‹br›");
document.write("‹b›jObj3.notsure:‹/b› " + jObj3.notsure +"‹br›");

‹/script›

The displayed output when this code is browsed is as shown in the next picture.


JSON Array

Unlike JSON objects, JSON arrays are enclosed between square braces [ ]. The JSON array is an ordered sequence of values separated by a comma (,). The values can be any of the primitive types as well as the two structures, JSON objects and JSON arrays. Here is a JSON array variable with four string values.

var myJsonArray=["Red", "Blue", "Yellow", "Magenta"];

You will be able to access an array item from its position (0 based) as shown in the following listing.

‹SCRIPT LANGUAGE="JavaScript"›
var myJsonArray=["Red", "Blue", "Yellow", "Magenta"];
for (i=0; i‹4; i++){
document.write("‹b›myJsonArray["+i+"]‹/b›="+ myJsonArray[i]+"‹br›");
}
‹/SCRIPT›

The displayed output when this script is executed is as shown in the next picture.


It is possible to have an array  whose elements are of different types. Array items can be objects and arrays as well, as shown in the next listing.
‹SCRIPT LANGUAGE="JavaScript"›
//Array with different types
myJA2=["red", 1, null, true];
document.write("‹;b›myJA2:‹;/b›  " + myJA2[2]);
document.write("‹;p›‹;/p›");
//Nested array
myJA3=["red",1,["a", "b", "c"], false];
document.write("‹;b›myJA3[2][1]:‹;/b›  " + myJA3[2][1]);
document.write("‹;p›‹;/p›");
//Object in an array
myJA4=["red", {"Yes":"Yes, you do", "No":"No, you do not"}, 2];
document.write("‹;b›myJA4[1].Yes: ‹;/b›"+ myJA4[1].Yes);
‹;/SCRIPT›

The displayed output when this script is executed is as shown in the next picture.


Notice how the inner array and the object inside the array are  accessed.
JSON and XML
JSON is minimal textual representation of data as compared to the “verbose” XML, which makes equivalent XML much larger than JSON. Well, both are textual, but JSON is more so than XML with all its “angularities.” This is not to put down XML but just to highlight the obvious. This has obvious implications for AJAX, and more often JSON is the preferred data format in which AJAX results are received.
Everything in XML is a string but JSON has types as discussed earlier. JSON equivalent of XML In my previous tutorials, XML Islands and XML Responses and AJAX, the file webstudents.xml was used for illustration.

The same file will be represented as a JSON object in this section. The file is reproduced here for reference. In writing down the equivalence only the root element and its children are considered. Here is the listing of webstudents.xml.
‹wclass›
‹!--My students who took web programming class with me--›
‹student id="1"›
‹name›Linda Jones‹/name›
‹legacySkill› Access, VB5.0‹/legacySkill›
‹/student›
‹student id="2"›
‹name›Adam Davidson‹/name;
‹legacySkill›Cobol, MainFrame‹/legacySkill›
‹/student›
‹student id="3"›
‹name›;Charles Boyer‹/name›
‹legacySkill›HTML, Photoshop‹/legacySkill›
‹/student›
‹student id="4"›
‹name›Charles Mann‹/name›
‹legacySkill›Cobol, MainFrame‹;/legacySkill›
‹/student›
‹/wclass›

The rules in this conversion are simple. The root element will be the main object, and the three student nodes will form an array. Each array element will be a student object with its own attributes as a string value pair. If you keep the following syntax  in your cross-hairs it will be easy to follow the listing.

Object: var obj={key1:value1, key2:value2 ,key3:value3};
Array: var Arr=[valueA, valueB, valueC];

The XML document has both simple and complex types and this is developed piecewise to make the explanation easy to understand.

Root element with students and their attributes

The root element is the object with the three students arranged in an array. Each of the students is an object as shown in the next listing.

‹SCRIPT LANGUAGE="JavaScript"›
var justStudents={"wclass":[
{"student":{"id":"1"}},
{"student":{"id":"2"}},
{"student":{"id":"3"}}
]}
alert(justStudents.wclass[1].student.id);
‹/SCRIPT›
This is an object whose value is an array. The wclass[1] refers to the second student object and is accessed as shown in the alert statement. This code will display an alert window with value 2. In the above code the children of the students are not included.
Root element with student’s children

The next listing shows the JSON object with only the children of students shown in an array.

‹SCRIPT LANGUAGE="JavaScript"›
var webclass ={
"wclass":[
{"student":
{"name":"Linda Jones", "legacySkill":"Access, VB 5.0"}},
{"student":
{"name":"Adam Davidson", "legacySkill":"Cobol, MainFrame"}},
{"student":
{"name":"Charles Boyer", "legacySkill":"HTML, XML"}}
]
};
alert(webclass.wclass[1].student.legacySkill);
‹/SCRIPT›

Here student 2 is “Charles Boyer” and his legacyskill is displayed in the alert box. Combining the two, it is easy to see how the JSON equivalent of webstudents.xml can be fashioned as shown in the next listing.
‹SCRIPT LANGUAGE="JavaScript"›
var studentAll={"wclass":[
{"student":{"id":"1"},"name":"Linda Jones",

"legacySkill":"Access, VB 5.0"},
{"student":{"id":"2"},"name":"Adam Davidson",

"legacySkill":"Cobol, MainFrame"},
{"student":{"id":"3"},"name":"Charles Boyer",

"legacySkill":"HTML, XML"}
]};
document.write("‹b›Id of 3rd student: ‹/b›" + studentAll.wclass[2].

student.id);
document.write("‹br/›");
document.write("‹b›name of 2nd student:‹/b› " + studentAll.wclass[1].

name);
document.write("‹br/›");
document.write("‹b›legacySkill of 1st student:‹/b› " + studentAll.

wclass[0].legacySkill);
‹/SCRIPT›

The listing also shows how the various values are accessed. The displayed output when this script is executed is as shown in the next picture.


Notice how the student attributes are accessed.

What about binary object representation?

There is no native support for binary objects. However some new formats have appeared recently.
Read here and here. However their universal adoption will take time.

Summary

JavaScript Object Notation (RFC 4627) is introduced with examples of its types, objects and structures in this post. JSON is well suited for data interchange. JSON is stable because it has no versions; needs no validation; and is not extensible, all very likable characteristics which may make it a long time player in JavaScript.

However, since JSON is a subset of JavaScript, it has to conform to the same naming conventions regarding the use of language specific keywords and other rules. Also, its usefulness in AJAX calls is obvious because JSON is as easy for humans as it is for machines, and a lot simpler and more understandable. he fact that it is easy for machines makes it an obvious for the Internet of Things where communication with machines takes center stage.

In the simple example of webstudents.xml, the number of characters for XML amounted to 413, whereas when formatted in JSON it required 243, a substantial difference. Accessing values is also a lot simpler than going through the ECMA object model climbing up and down the XML tree.

Unmodified version of the post appeared here:
http://www.devarticles.com/c/a/JavaScript/JSON-Basics/2/

No comments: