0% found this document useful (0 votes)
5 views

Json

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Json

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

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”

• Arrays in JavaScript are not typed, they can be used


to store any number of different datatypes.
o var aValues = [“string”, 24, true, null];

• This array contains a string, followed by a number,


followed by a Boolean, followed by a null value.
• This is completely legal and perfectly fine
JavaScript.
Object literals
• Object literals are used to store information in name-
value pairs, ultimately creating an object.
• An object literal is defined by two curly braces ( { and } ).
• For example:
var oCar = {
“color” : “red”,
“doors” : 4,
“paidFor” : true
};

• This code creates an object with three properties named


color, doors, and paidFor, each containing different
values. These properties are accessed by using the
object name and dot notation, such as:
alert(oCar.color); //outputs “red”
alert(oCar.doors); //outputs “4”
alert(oCar.paidFor); //outputs “true”

• Bracket notation can also be used by passing in the


name of the property as a string value.
alert(oCar[“color”]); //outputs “red”

alert(oCar[“doors”]); //outputs “4”

alert(oCar[“paidFor”]); //outputs “true”

• The same object could be created using the


JavaScript Object constructor, like this
var oCar = new Object();
oCar.color = “red”;
oCar.doors = 4;
oCar.paidFor = true;
Mixing literals
• It’s possible to mix object and array literals, creating an array of objects or
an object containing an array.
var aCars = [
• This code defines an array, aCars, which has three objects
{
in it. The three objects each have properties named color,
“color” : “red”,
doors, and paidFor.
“doors” : 2, • The information in the array is accessible by using a
“paidFor” : true combination of bracket and dot notation.
}, • alert(aCars[1].doors); //outputs “4”
{
“color” : “blue”, • You can also define the array to be inside of object literals,
“doors” : 4, such as:
“paidFor” : true var oCarInfo = {
}, “availableColors” : [ “red”, “white”, “blue” ],
{ “availableDoors” : [ 2, 4 ]
“color” : “white”, };
“doors” : 2, • This code defines an object called oCarInfo that has two
“paidFor” : false properties, availableColors and availableDoors. Both of
} these properties are arrays, containing strings and
numbers, respectively
];
JSON Syntax
• JSON syntax is really nothing more than the mixture of object and
array literals to store data.
• The only difference from the examples in the last section is that
JSON doesn’t have variables.
• JSON represents only data; it has no concept of variables,
assignments, or equality.
• Example: {
“availableColors” : [ “red”, “white”, “blue” ],
“availableDoors” : [ 2, 4 ]
}

• 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”

o alert(oCarInfo.availableDoors[1]); //ouputs “4”

• There are obvious benefits to using JSON as a data format for


JavaScript communication: it takes the evaluation of the data
out of your hands and, therefore, grants you faster access to
the information contained within.
JSON Encoding/Decoding
• To aid JavaScript developers with JSON usage, Crockford has written a
JavaScript library that adds several methods for translating data between JSON
and JavaScript.
• Unlike other JavaScript libraries, this one takes advantage of JavaScript’s
extensibility, adding methods to Object, Array, and String.
• The first method is parseJSON(), which is accessible on any string. For instance,
if you have a string sJSON that contains JSON code, it can be translated into a
JavaScript object like this:
o var oObject = sJSON.parseJSON();

• 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:

• This code outputs the following JSON string:

• The ability to encode and decode between JavaScript and JSON is an


important ability and one that Crockford’s library provides in a secure
manner.

• 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.

• Consider the following XML data:


• This example contains information
about three students in a class.
• Right away, there is some XML
information that isn’t entirely necessary:
the <classinfo> and <students/>
elements.
• These elements help to define the
overall structure and meaning of the
information, but the actual information
you’re interested in is the students and
their information.
• For each piece of information about the
students, the name of the information is
repeated twice, although the actual data
appears only once.
• Consider the same information formatted as JSON:

• A lot of the superfluous information


isn’t present in this JSON form.
• Closing tags aren’t necessary to match
opening tags, this greatly reduces the
number of bytes needed to transmit the
same information.
• Not including spaces, the JSON data is 224
bytes, whereas the comparable XML data
is 365 bytes, saving more than 100 bytes.
• The disadvantage to JSON-formatted data as compared to XML is that it’s far
less readable to the naked eye. Because XML is verbose, it’s fairly easy to
understand what data is being represented with a simple glance.

• 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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy