Json
Json
Chapter – 8
Professional Ajax 2nd Edition by Nicholas C. Zakas, Jeremy
McPeak and Joe Fawcett
What is JSON?
• JSON is a very lightweight data format based on a
subset of the JavaScript syntax, namely array and
object literals.
• It uses JavaScript syntax, JSON definitions can be
included within JavaScript files and accessed without
the extra parsing that comes with XML-based
languages.
• But before user can use JSON, it’s important to
understand the specific JavaScript syntax for array
and object literals.
Array literals
• Array literals are specified by using square brackets
( [ and ] ) to enclose a comma-delimited list of
JavaScript values (meaning a string, number,
Boolean, or null value), such as:
• var aNames = [“Benjamin”, “Michael”, “Scott”];
• This is functionally equivalent to the following, more
traditional form:
• var aNames = new Array(“Benjamin”, “Michael”,
“Scott”);
• Values are accessed in the array by using the array
name and bracket notation:
o alert(aNames[0]); //outputs “Benjamin”
o alert(aNames[1]); //outputs “Michael”
o alert(aNames[2]); //outputs “Scott”
• Note that the variable oCarInfo has been removed, as has the
semicolon following the closing curly brace.
• If this data were transmitted via HTTP to a browser, it would be
fairly quick because of the small number of characters.
• To transform it into an object, simply use the JavaScript eval()
function: var oCarInfo = eval(“(“ + sJSON + “)”);
• This example surrounds the JSON text with parentheses and
then passes that string into the eval() function, which acts like a
JavaScript interpreter. The result of this operation is a
JavaScript object identical to the oCarInfo object.
o alert(oCarInfo.availableColors[0]); //outputs “red”
• This method provides safer evaluation of JSON code than eval(), which
evaluates all JavaScript code and could potentially allow the execution of
arbitrary code.
• The parseJSON() method ensures that the JSON code contains only data and will
not result in code being executed.
• The library also adds the toJSONString() method to all objects, including
Array. This method recursively serializes any object into a JSON string.
Consider the following example:
• With this tool, you’re now ready to use JSON in an enterprise-level web
application.
JSON versus XML
• One of the advantages of JSON over XML is that it’s more compact. XML is
considered by some to be overly verbose for its purpose.
• JSON, with its shorthand notation, can be difficult to decipher without other
software tools.
• An argument can be made that data exchange formats should never be viewed
with the naked eye. Thus, it makes sense that server-side JSON tools are
necessary to create the data being sent to the client.