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.
Sometimes, it’s possible that too many tags can make a document hard to read, especially for developers.
A large number of developers know this language and in almost all cases it is quite easy to manipulate.
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.
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, whichrequires a more in-depth look.
First look at the structure
var person = { "name" : "Nicolas" , "age" : "22" , "alive" : true , "gender" : "Male" , "power" : "1" } |
In the above example we created a new variable, and inserting all of its content inside the braces, we have indicated thatit’s indeed an object. Inside the object we have inserted several properties, the end result being:
'nome-proprietà ' : 'valore-proprietà ' |
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
console.log( person.age ); // logs = 22 console.log( person.gender ); // logs = Male console.log( person.name + ' ha ' + person.age + ' anni' ); |
note: the code you just saw will be executed only when the browser console is active.
- how to activate the console in Google Chrome: View > Options for developers > JavaScript Console
- how to activate the console in Opera: Tools> Advanced > Tools for developers
- 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:
< persone > < persona > < name >Nicolas</ name > < age >22</ age > < alive >true</ alive > < gender >Male</ gender > < power >1</ power > </ persona > </ persone > |
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
"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:
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:
var persone = { "nicolas" : { "name" : "Nicolas" , "age" : "22" }, "piero" : { "name" : "Piero" , "age" : "29" }, "gianni" : { "name" : "Gianni" , "age" : "20" } } |
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:
Let’s take a look at how we can use this data:
alert(persone.nicolas.name); // alert: Nicolas alert(persone.piero.name); // alert: Pierto alert(persone.piero.age); // alert: 29 alert(persone.gianni.age) // alert: 20 |
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:
[ { "name" : "Nicolas" , "age" : "22" }, { "name" : "Piero" , "age" : "29" }, { "name" : "Gianni" , "age" : "20" } ] |
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:
In order to fully use all of the data found inside the persons array, we could employ a ‘for’ cycle, in the following way:
var output = '' ; for ( var i = 0 ; i < persone.length; i++) { output += persone[i].name + ' ha ' + persone[i].age + ' anni<br />' ; } |
At the end of the ‘for’ cycle, the result of the output variable will be the following:
Nicolas is 22 years old Piero is 29 years old Gianni is 20 years old |
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.
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.
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 parsinginside 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.
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:
The code you would use could be similar to this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> < head > < title >Column 1.0 - Your Inspiration Web</ title > < meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" /> < script type = "text/javascript" src = "./js/jquery-1.4.min.js" ></ script > < script type = "text/javascript" src = "./js/site.js" ></ script > < link rel = "stylesheet" href = "./style/screen.css" type = "text/css" media = "all" /> </ head > < body > <!-- contenuto html --> </ body > </ html > |
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:
Let’s create a new file named json.php and we’ll insert the following code inside the file:
[ { "fname" : "Nicolas" , "lname" : "Gutierrez" , "age" : 22, "web" : "yourinspirationweb.com" , "number" : "0065 5402468" }, { "fname" : "Mario" , "lname" : "Bros" , "age" : 24, "web" : "mariobros.com" , "number" : "0024 1291932" }, { "fname" : "John" , "lname" : "Resig" , "age" : 25, "web" : "ejohn.org" , "number" : "0010 5102012" } ] |
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:
Let’s create a new file named site.js and insert the following code:
$(document).ready( function (){ $.getJSON( './json.php' , function (data){ // ciclo l'array for (i=0; i<data.length; i++){ var content = '<li> '; content += data[i].fname + ' ' + data[i].lname; content += ' <br /> '; content += data[i].number; content += ' </li> '; $(' ul.rubrica').append(content); } } ); } ); |
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.
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:
- The file’s address which receives the request
- one parameter to switch from get to file
- 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.
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:
data[index_element].property |
where index_element is defined by the i variable and the property names are those inserted in the file json.php.
Inside the for cycle, to access each property of the object we will use the following code:
data[i].fname // name data[i].lname // last name data[i].age // age |
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.
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.
No comments:
Post a Comment