Search This Blog

Wednesday, June 17, 2009

JavaScript Object Notation (JSON)

Abstract

JavaScript Object Notation (JSON) is a lightweight, text-based,
language-independent data interchange format.  It was derived from
the ECMAScript Programming Language Standard.  JSON defines a small
set of formatting rules for the portable representation of structured
data.

1. Introduction

JavaScript Object Notation (JSON) is a text format for the serialization of structured data. It is derived from the object literals of JavaScript, as defined in the ECMAScript Programming Language Standard, Third Edition [ECMA]. JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays). A string is a sequence of zero or more Unicode characters [UNICODE]. An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array. An array is an ordered sequence of zero or more values. The terms "object" and "array" come from the conventions of JavaScript. JSON's design goals were for it to be minimal, portable, textual, and a subset of JavaScript.

Why JSON?

The benefit of JSON is that it is recognized natively by JavaScript. No need for parsing an XML document to extract the data and get it throught the net.

JSON and XML

Benefits of JSON: - The easiness of reading. - The easiness of using. Benefits of XML: - XML is extensible. - It is widely used and recognized by almost all programming languages. Unfortunally, both XML and JSON are enable to integrate a large amount of data in binary form.

The syntax of JSON

The components of JSON: - An object: contains objets or attributes. - A scalar variable: Number, String, Boolean. - An array. - Literal values: null, true, false, "string of characters", and numerical values.

Object

It contains a member or a list of members, and each member has the form:

"name" : "value"

The syntax of the object is:

{ member, member, .... }

Array

A collection of values, separated by commas. [ value, value, ....]

Values

A value may be: an object, an array, a litteral (string, number, true, false, null).

Nothing more is required to create a JSON file!

Example of JSON file

A simple example, designing a menu: It is an object made of members that are an attribute and an array that holds other objects, the rows of the menu.


{
"menu": "File",
"commands": [
    {
        "title": "New",
        "action":"CreateDoc"
    },
    {
        "title": "Open",
        "action": "OpenDoc"
    },
    {
        "title": "Close",
        "action": "CloseDoc"
    }
 ]
}
The XML equivalent:
<?xml version="1.0" ?>
<root>
<menu>File</menu>

<commands>
   <item>
       <title>New</value>
       <action>CreateDoc</action>
   </item>

   <item>
       <title>Open</value>
       <action>OpenDoc</action>
   </item>
   <item>

       <title>Close</value>
       <action>CloseDoc</action>
   </item>
</commands>
</root>

How to use the format

The JSON file allows to load data from the server or to send data to it, in this format. For example, storing the content of a form, just filled by an user. This involves three steps: the browser processing, the server processing, and the data exchange between them.

Client side (browser)

This is rather easy, as JSON is a part of the JavaScript definition. The content of a file, or the definition of the data is assigned to a variable, and this variable becomes an object of the program.

Server side

JSON file are used by various programming languages, including PHP and Java thanks to parsers that allow to get the content and that may even convert it into classes and attributes of the language. The json.org includes a C parser and a list of parsers in other languages.

Data exchange

Loading a file may be accomplished from JavaScript in several ways: - direct including of the file into the HTML page, as a JavaScript .js external file. - loading by a JavaScript command. - using XMLHttpRequest. The JSON file is parsed by the eval() JavaScript function. Sending the file to the server may be accomplished by XMLHttpRequest. The file is sent as a text file and processed by the parser of the programming language that uses it.

Example

The XMLHttpRequest code:

var req = new XMLHttpRequest();
req.open("GET", "file.json", true);
req.onreadystatechange = myCode;   // the handler
req.send(null); 

The JavaScript handler:

function myCode()
{
 if (req.readyState == 4)
 {
      var doc = eval('(' + req.responseText + ')');
 }
}
Using the data:
var menuName = document.getElementById('jsmenu');   // finding a field
menuName.value = doc.menu.value;           // assigning a value to the field
How to access data:
doc.commands[0].title      // read value of the "title" field in the array
doc.commands[0].action     // read value of the "action" field in the array

For a Demo click here:

No comments: