JavaScript Object Notation

From Citizendium
Revision as of 13:59, 19 August 2010 by imported>Pat Palmer
Jump to navigation Jump to search
This article is developing and not approved.
Main Article
Discussion
Definition [?]
Related Articles  [?]
Bibliography  [?]
External Links  [?]
Citable Version  [?]
 
This editable Main Article is under development and subject to a disclaimer.

JavaScript Object Notation (JSON) and has been a part of JavaScript since December 1999, but it wasn't until 2005 that, along with the rise of AJAX, JSON was discovered to be a useful data interchange format. Many APIs have embraced JSON, and major frameworks such as .NET now offer JSON as an option in the output response for web services. JSON also has a media type - appplication/json and a file type of .json.

Benefits and drawbacks of JSON

Benefits

One major benefit of JSON is it is easily readable, like XML, but unlike XML is not so bulky. Some may argue that the size of JSON outputs compared to XML doesn't always have a markedly advantage. However, in the context of an application where polling or frequent updates are made, the lightweight JSON does is hard to beat. Another advantage over XML and most over data interchange formats is that it is easily converted to an JavaScript object. Working with objects is much easier than traversing the Document Object Model (XML) of an XML document or parsing text. In the case of AJAX, the client script could easily create the object and manipulate it and/or other objects within the document.

Drawbacks

One has to consider the source of the JSON output before using the Javascript native function 'eval' - which could execute malicious script. Common sense would dictate that only use JSON from a trusted source.

Other drawback, is when you initiate a javascript object via literal notation it does not call any constructor methods. The object may contains property values that do not match their data type, and this might cause a problem for other objects and/or methods consuming them. JSON also does not have a easy way to handle binary content type such as images.

Structure of JSON

JSON is comprised of two simple structures: name/value pairs and collections or lists of values. Eavery object is a list of pairs which are encapsulated with curly braces "{}." Each named pair starts with it name within quotes followed a semicolon and next its value. Each name/value pair is separated by a comma. Arrays are formatted as name in quotes, than ":" semicolon followed by a brackets which contain the list of values separated by commas. See the Json.org [1] website for a detailed format/structure of JSON.

For Example: json='{ "FirstName":"Brian","LastName":"Caputo","Grades":[95,98,96,93]}';

var Stud1 = eval('('+json+')'); Now Stud1 is an object we can type Stud1.FirstName and the value should