Вы находитесь на странице: 1из 9

Page 1 of 9

04/28/10 - Do you want to use JSON but don't know where to start?

As time passes, and as 2.0 web applications become more popular, AJAX has
become leader in the transfer of asynchronous data.
Having said that, it has become evident that there's a need for a language which is
versatile, easy to use and able to communicate with various programming
languages: JSON has all of these characteristics.
In this article we will discover JSON, its syntax and show you an example of how it
should be used inside a web application.

What's JSON ?

JSON stands for JavaScript Object Notation and it is a type of format which stores
various types of information, and allows this information to be shared between
client and server applications.

One of its strenghts is in regards to data writing and data analysis; developers
using this format will benefit considerably from this characteristic.

In confirmation of what we've just said, Yahoo! supports JSON as an alternative of


its own web services since 2005, and many other applications also support it.

XML or JSON ?

XML has many advantages, for instance, it is highly versatile making it adaptable
to every kind of situation; we can use xml by creating new tags and nesting them
regardless of the type of project we're working on.
A large number of developers know this language and in almost all cases it is
quite easy to manipulate.
Page 2 of 9

Sometimes, it's possible that too many tags can make a document hard to read,
especially for developers.

JSON has a very simple structure, which a developer can read easily even upon
first sight; this is not something you want to underestimate, especially when one's
working on large projects involving more people.
The JSON/JavaScript combination is perfect since all the information retrieved from
JSON can be used in JavaScript by using the eval() function. This function verifies
that a parameter passing through it is a valid string. In case it's positive, the function
does a pairing of the string looking for JavaScript code.

This does not mean that XML is better than JSON or viceversa; JSON is a really
simple and versatile language to use, which requires a more in-depth look.

First look at the structure

Arrayvar person = {Array"name" : "Nicolas",Array"age" :


"22",Array"alive" : true,Array"gender" :
"Male",Array"power" : "1"Array}Array

In the above example we created a new variable, and inserting all of its content
inside the braces, we have indicated that it's indeed an object. Inside the object
we have inserted several properties, the end result being:

Array'nome-proprietà' : 'valore-proprietà'Array

note: remember to use a comma to separate one property from another, while the
last property does not need to be followed by a comma.

In JavaScript, in order to use one of the defined properties inside the object
"person", one has to rely on the following syntax: nameobject.nameproperty

Arrayconsole.log( person.age ); // logs = 22Arrayconsole.log(


person.gender ); // logs = MaleArrayArrayconsole.log(
person.name + ' ha ' + person.age + ' anni' );Array

note: the code you just saw will be executed only when the browser console is
active.
Page 3 of 9

1. how to activate the console in Google Chrome: View > Options for
developers > JavaScript Console
2. how to activate the console in Opera: Tools> Advanced > Tools for
developers
3. how to activate the console in Firefox: Tools> Error console

The example we just saw could be re-proposed in xml, with a similar-looking


structure:

Array<persone>Array<persona>Array<name>Nicolas</name>Array
<age>22</age>Array<alive>true</alive>Array
<gender>Male</gender>Array
<power>1</power>Array</persona>Array</persone>Array

This example is quite ordinary, but on a first-look basis JSON reveals itself to be
clear and simple.

Data types

JSON supports the following types of data:

• Boolean ( true e false )

"active" : true

• Numbers

"age" : '22'

• Strings
Page 4 of 9

"nome" : "Nicolas"

• Arrays

"data" : [28, 02, 2010]

• Objects

"info" : {web: "Your Inspiration Web"}

The structure is very clear which allows us to read and understand the code.

In the previous example we created a small JSON object which contains a series
of attributes.

JSON is based on two structures: the first one -which we just looked at ? is an
object; the second one involves arrays. Objects are a group of un-arranged names
and values, while arrays are a group of ordered values.

Nest objects

In the first example we saw how to create an object with names and values that
provide information about a person.
If there's more than one person for whom we need to insert such data, we could
nest more than one object.
Let's take a look at the following example to see how it works:

Arrayvar persone = {Array"nicolas" : {Array"name" :


"Nicolas",Array"age" : "22"Array },Array"piero" :
{Array"name" : "Piero",Array"age" :
"29"Array},Array"gianni" : {Array"name" :
"Gianni",Array"age" : "20"Array}Array}Array
Page 5 of 9

In this case, the object person contains three properties: nicolas, piero, and
gianni. These three are objects that contain a series of names/values.
Let's take a look at how we can use this data:

Arrayalert(persone.nicolas.name); // alert:
NicolasArrayalert(persone.piero.name); // alert:
PiertoArrayalert(persone.piero.age); // alert:
29Arrayalert(persone.gianni.age) // alert: 20Array

This example contains data that is more complex than the one in the first example,
however it must be noted how the structure remains clear and simple.

How to store data using Arrays

As we've seen before, arrays are another structure one can use to store data in
JSON. Let's look at a simple example:

Array[Array{Array"name" : "Nicolas",Array"age" :
"22"Array },Array {Array"name" : "Piero",Array"age"
: "29"Array },Array {Array"name" :
"Gianni",Array"age" : "20"Array}Array]Array

In this example we were able to create an array named "persons", and each
value of the array is an object which contains two pairs of names/values: name and
age.
In order to fully use all of the data found inside the persons array, we could employ
a ?for' cycle, in the following way:

Arrayvar output = '';Arrayfor (var i = 0 ; i <


persone.length; i++) {Arrayoutput += persone[i].name + ' ha '
+ persone[i].age + ' anni<br />';Array}Array

At the end of the ?for' cycle, the result of the output variable will be the following:

ArrayNicolas is 22 years oldArrayPiero is 29 years


oldArrayGianni is 20 years oldArray
Page 6 of 9

Brief summary

We've seen how clear and simple the syntax used in JSON is.
With the proliferation of AJAX, an almost "universal" language -one that can act as
an intermediary between different programming languages -has become a
necessity.

As a matter of fact, JSON can also be used to employ ajax in a cross-domain mode,
something that is not provided by any program natively.

In JavaScript, JSON must be processed through the eval() function so that simple
strings of text can be interpreted and not considered as just text.
Eval() has a small problem: it increases loading times, since it has to re-elaborate
all of the JSON content. Also, this approach is not completely safe, since it has to
interpret everything which will be "transformed" into JavaScript code.
What this means is that a potential hacker could insert several JavaScript strings in
what should be just some simple JSON. These JavaScript strings would then be
interpreted correctly using the eval() function.

On the JSON website, at the end of the page, you can find many libraries that you
can use to execute the JSON parsing inside your favorite programming language.
In fact, several JavaScript libraries do not rely on the eval() function when effecting
a parsing of JSON.

Practical use

In the following example we will use JSON to transfer data and visualize it in our
web application (to keep it simple, in our guide we will use the jQuery library).
You can find a demo showing you what we've done by clicking here.

Let's pretend you have to compile a list, like a phonebook, that needs to be
generated dynamically by uploading data inside the list using JSON.

Start with XHTML and jQuery

To begin with, you will need an xhtml page, the latest version of jQuery and a
JavaScript file in which the script will be added.
The code you would use could be similar to this:
Page 7 of 9

Array<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0


Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">Arra
y<html
xmlns="http://www.w3.org/1999/xhtml">Array<head>Array<title>C
olumn 1.0 - Your Inspiration Web</title>ArrayArray<meta
http-equiv="Content-Type" content="text/html; charset=UTF-8"
/>ArrayArray<script type="text/javascript"
src="./js/jquery-1.4.min.js"></script>Array<script
type="text/javascript"
src="./js/site.js"></script>ArrayArray<link rel="stylesheet"
href="./style/screen.css" type="text/css" media="all"
/>Array</head>Array<body>ArrayArray<!-- contenuto html
-->ArrayArray</body>Array</html>Array

Now you will need a file containing the JSON code; in this example we'll use a file
php which could generate dynamically all the needed code.
Let's create a new file named json.php and we'll insert the following code inside the
file:

Array[Array{Array"fname": "Nicolas",Array"lname":
"Gutierrez",Array"age": 22,Array"web":
"yourinspirationweb.com",Array"number": "0065
5402468"Array },Array{Array"fname":
"Mario",Array"lname": "Bros",Array"age":
24,Array"web": "mariobros.com",Array"number": "0024
1291932"Array },Array{Array"fname":
"John",Array"lname": "Resig",Array"age":
25,Array"web": "ejohn.org",Array"number": "0010
5102012"Array}Array]Array

In the code you can see how we've created an Array containing three elements;
these elements are in turn objects containing a series of properties/values.

Once you've created the json.php file, the only thing left is to create the script
responsible of charging and re-elaborating its content.
Let's create a new file named site.js and insert the following code:

Array$(document).ready(Arrayfunction(){Array$.getJSON(Array
Page 8 of 9

'./json.php',Arrayfunction(data){Array// ciclo
l'arrayArrayfor(i=0; i<data.length; i++){Arrayvar
content = '<li>';Array content += data[i].fname + ' '
+ data[i].lname;Array content += '<br />';Array
content += data[i].number;Array content +=
'</li>';ArrayArray$('ul.rubrica').append(content);Array
}ArrayArray}Array);Array}Array);Array

All of the script has been entered inside the ready() method of jQuery, which in turn
executes the content only after the DOM has been fully loaded.
You should note how inside the ready() method, theres the getJSON() method being
used.
This method loads data in JSON format from the server, using an HTTP request
of type GET.

The getJSON method accepts three parameters:

1. The file's address which receives the request


2. one parameter to switch from get to file
3. a call back function to use the resulting content

We will use only two parameters: the address (./json.php) and the callback function.
The callback function has a paramater - variabile data ? which contains all of the
JSON code from the request that is already re-elaborated. This means that a
parsing of the code has been effected so that Objects and Arrays can be used
normally in JavaScript.

You should notice how inside the callback function there's a for cycle which begins
from or until the i variable reaches a value < (less than) the total number of elements
inside the Array (in this case 3).

Inside each element of the array we can find, as we've said before, an object
containing properties and values which we can access the following way:

Arraydata[index_element].propertyArray

where index_element is defined by the i variable and the property names are those
Page 9 of 9

inserted in the file json.php.

Inside the for cycle, to access each property of the object we will use the following
code:

Arraydata[i].fname // nameArraydata[i].lname // last


nameArraydata[i].age // ageArray

and so on for all the other available properties.

In our example we created a variable (content) in which a <li> is inserted that


contains: Name, Last name and contact's phone number.
This variable is then passed on as a parameter to jQuery's append() method which
inserts the content inside the selected element, specified in the selector -in this
case all of the <ul> which are class ?column' ( $(?ul.column') );
The net result is a series of <li> containing the full names of people in our
phonebook.

Final thoughts

The example we looked at in this article is really simple, but it shows you how easy
it is to work with JSON.
Now that you've seen how easy it is to use JSON in our own applications, do you
think you will use it in the future?

Author : Yong Mook Kim

Website : http://www.mkyong.com/blog/adsense-daemon-wordpress-plugin/ -->

Вам также может понравиться