Professional Documents
Culture Documents
JSON is syntax for storing and exchanging text information. Much like XML.
JSON is smaller than XML, and faster and easier to parse.
JSON Example
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
The employees object is an array of 3 employee records (objects).
What is JSON?
* JSON uses JavaScript syntax for describing data objects, but JSON is still language and
platform independent. JSON parsers and JSON libraries exists for many different
programming languages.
JSON - Introduction
With our editor, you can edit JavaScript code online and click on a button to view the result:
JSON Example
<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p>
Name: <span id="jname"></span><br />
Age: <span id="jage"></span><br />
Address: <span id="jstreet"></span><br />
Phone: <span id="jphone"></span><br />
</p>
<script>
var JSONObject= {
"name":"John Johnson",
"street":"Oslo West 555",
"age":33,
"phone":"555 1234567"};
document.getElementById("jname").innerHTML=JSONObject.name
document.getElementById("jage").innerHTML=JSONObject.age
document.getElementById("jstreet").innerHTML=JSONObject.street
document.getElementById("jphone").innerHTML=JSONObject.phone
</script>
</body>
</html>
Result
No end tag
Shorter
Uses arrays
No reserved words
Why JSON?
For AJAX applications, JSON is faster and easier than XML:
Using XML
Using JSON
JSON Syntax
Previous
Next Chapter
"firstName" : "John"
This is simple to understand, and equals to the JavaScript statement:
firstName = "John"
JSON Values
JSON values can be:
null
JSON Objects
JSON objects are written inside curly brackets,
Objects can contain multiple name/values pairs:
{ "firstName":"John" , "lastName":"Doe" }
This is also simple to understand, and equals to the JavaScript statements:
firstName = "John"
lastName = "Doe"
JSON Arrays
JSON arrays are written inside square brackets.
An array can contain multiple objects:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
In the example above, the object "employees" is an array containing three objects. Each
object is a record of a person (with a first name and a last name).
Because JSON uses JavaScript syntax, no extra software is needed to work with JSON within
JavaScript.
With JavaScript you can create an array of objects and assign data to it like this:
Example
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];
The first entry in the JavaScript object array can be accessed like this:
John Doe
The data can be modified like this:
employees[0].firstName = "Gilbert";
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>Original name: <span id="origname"></span></p>
<p>New name: <span id="newname"></span></p>
<script>
var employees = [
{ "firstName" : "John" , "lastName" : "Doe" },
{ "firstName" : "Anna" , "lastName" : "Smith" },
{ "firstName" : "Peter" , "lastName" : "Jones" }, ];
</body>
</html>
result:-
JSON Files
JSON HowTo
Previous
Next Chapter
Example
<p>
First Name: <span id="fname"></span><br />
Last Name: <span id="lname"></span><br />
</p>
<script>
document.getElementById("fname").innerHTML = obj.employees[1].firstName
document.getElementById("lname").innerHTML = obj.employees[1].lastName
</script>
Try it yourself
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br>
Last Name: <span id="lname"></span><br>
</p>
<script>
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
document.getElementById("fname").innerHTML=obj.employees[1].firstName
document.getElementById("lname").innerHTML=obj.employees[1].lastName
</script>
</body>
</html>
Result:Create Object from JSON String
JSON Parser
The eval() function can compile and execute any JavaScript. This represents a potential security pro
It is safer to use a JSON parser to convert a JSON text to a JavaScript object. A JSON parser
will recognize only JSON text and will not compile scripts.
In browsers that provide native JSON support, JSON parsers are also faster.
Native JSON support is included in newer browsers and in the newest ECMAScript
(JavaScript) standard.
Web Browsers Support
jQuery
Internet Explorer 8
Yahoo UI
Chrome
Prototype
Opera 10
Dojo
Safari 4
ECMAScript 1.5
Try it yourself
Its compact
Its easy for both computers and people to read and write
It maps very easily onto the data structures used by most programming
languages (numbers, strings, booleans, nulls, arrays and associative
arrays)
Nearly all programming languages contain functions or libraries that can
read and write JSON structures
Note:
JSON stands for JavaScript Object Notation. As the name implies, its
based on the way you define objects (which are very similar to what
youd call associative arrays or hashes in other languages), and arrays.
How does it work?
JSON is capable of setting up data constructs for integers, strings, arrays, and
booleans the most essential data building blocks. Using a carefully defined
syntactical construct, JSON can be used to outline an object and with the use of
javascripts eval() function, they can be converted to a working object.
But the power does not end there. Other popular programming languages have
been implementing native support for JSON, such as PHP and ActionScript. For
example, PHP can now convert an associative array of data into a JSON string by
using the new json_encode() function, provided in version 5.2+ of the language.
For languages without native support, you can find a full range of
implementation classes available at the JSON website.
How to write JSON Syntax:
Declaration
All JSON objects are declared with a pair of curly braces. You can assign them to
a variable like you would any other data structure.
1var myObj = {}
Thats it! While not very powerful, this is all thats required to create
objects using JSON. So lets start adding some properties to this object.
Strings
We are going make this object represent me, so lets start by adding my name.
Lets take a second to carefully look at what we did here. We wanted to add a
property called name, and to do so, you simply write the property, name. We
follow the property label by a colon to separate the property name and its value.
To the right of the colon, comes the value. Since we wanted the value to be a
string, we put it in quotes.
With the JSON we have put in place, you are now able to access the property by
using the dot notation. To access a property, follow the Variable [dot] property
construct.
1alert(myObj.name) // "Nahid"
Integers
If we wanted to assign a property to the object of an integer data type, there is
no need to quote the value.
2
3
alert("My name is " + myObj.name + " and I'm " + myObj.age);
4
5
Booleans
Like integers, booleans are also unquoted
Arrays
Arrays can contain a collection of the previously mentioned data types. To define
an array, wrap the value in square brackets and separate the values with
commas.
Note: I will now add line breaks and indentation for legibility. It has no bearing
on the working order of the object.
1 var myObj = {
2
3 name: 'Nahid',
4
5 age: 24,
6
7 engaged: true,
8
9
1
0
1
}
1
You can access a value in an array in the object by using a combination of the
dot notation (to access the objects property) and index notation (to access an
indexed value of an array).
To take the array complexity one step further, an array can also contain other
objects.
1 var myObj = {
2
3 name: 'Nahid',
4
5 age: 24,
6
7 engaged: true,
8
9
1
0 family_members: [
1
1
1
2
1 {name: "Tina", age: 24, relation: "sister"}
3
1
4
1
5
1]
6
1
7}
1
8
1
9
This still requires dot and index notation, with an additional dot notation for
accessing the property of the object found in the indexed array value.
1alert(myObj.family_members[1].name) // "Tina"
There is one situation where you will use square brackets to access an objects
property and not the dot notation: when you are using a variable as the property
name. For example:
1 var myObj = {
2
3 name: 'Nahid',
4
5 age: 27,
6
7
8
9
1
0
1
1
engaged: true,
1
5
1
6
1]
7
1
}
8
1
9 var property = "age"
2
0
2
1
2
2
2
3
alert(myObj[property]); // "24"
Recap
Take some time experimenting with JSON and you will see that you can pick up
the concept and syntax rather quickly. As a caveat that may save you time in
the future: certain languages require you to quote the property names, such as
ActionScript. If not, it will complain.
2.
3.
1 <html>
2 <head>
3 <title>
4 Object creation in JSON in JavaScript
5
</title>
"age" : 23,
1
0
1
1
1
2
"phone"
: "011-4565763",
"MobileNo" : 0981100092
};
document.write("<h2><font color='blue'>Name</font>::"
+JSONObject.name+"</h2>");
1 document.write("<h2><font color='blue'>Address</font>::"
3
+JSONObject.address+"</h2>");
1 document.write("<h2><font color='blue'>Age</font>::"
4
+JSONObject.age+"</h2>");
1
5 document.write("<h2><font color='blue'>Phone No.</font>::"
1 +JSONObject.phone+"</h2>");
6 document.write("<h2><font color='blue'>Mobile No.</font>::"
1
7
+JSONObject.MobileNo+"</h2>");
</script>
1
8 </head>
1 <body>
9 <h3>Example of object creation in JSON in JavaScript</h3>
2 </body>
0
</html>
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
Output:
Name::Fahad
Address::420 Hatirpool
Age::23
Phone No.::011-4565763
Mobile No.::981100092
Example of object creation in JSON in JavaScript
Creating Array Objects in JavaScript with JSON
In This example we have created an object students which contains two
array objects Maths and Science containing name, marks and age of two
students. Now we can access these objects value in the following way:
students.Maths for accessing Maths array and students.Science for
accessing Sciencearray object. Now to access first element of the Maths array
we can write it as students.Maths[1]and then we can access elements of
this array as students.Maths[1].Name for name
1 <html>
2 <head>
3 <title>
4 Array JSON-JavaScript Example
5
6
7
</title>
<script language="javascript" >
var students = { "Maths" : [
8
9
1
0 "age" : 23 },
1 "age" : 21 }
2
],
1
3 "Science" : [
1 {"Name" : "Mizan", // First Element
4
"Marks" : 56,
1
"age" : 27 },
5
1
6
1 "age" : 41 }
7
1 ]
8
1
9
2
0 document.writeln("<table border='1'><tr>");
2 for(i=0;i<students.Maths.length;i++)
1
{
2
2
document.writeln("<td>");
document.writeln("<table border='0' width=100 >");
2
3
document.writeln("<tr><td><B>Name</B></td><td width=50>"
2
4
+students.Maths[i].Name+"</td></tr>");
2
5
+students.Maths[i].Marks +"</td></tr>");
document.writeln("<tr><td><B>Marks</B></td><td width=50>"
document.writeln("<tr><td><B>Age</B></td><td width=50>"
2
6
+students.Maths[i].age +"</td></tr>");
document.writeln("</table>");
2
7
document.writeln("</td>");
2 }
8
for(i=0;i<students.Science.length;i++)
2
9 {
3
0
3
1
3
2
3
3
3
document.writeln("<td>");
document.writeln("<table border='0' width=100 >");
document.writeln("<tr><td><B>Name</B></td><td width=50>"
+students.Science[i].Name+"</td></tr>");
document.writeln("<tr><td><B>Marks</B></td><td width=50>"
+students.Science[i].Marks +"</td></tr>");
document.writeln("<tr><td><B>Age</B></td><td width=50>"
+students.Science[i].age +"</td></tr>");
document.writeln("</table>");
3
5
document.writeln("</td>");
3 }
6
document.writeln("</tr></table>");
3
7 </script>
3 </head>
8 <body>
4
0 </html>
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0
Output:
PHP, like JavaScript, has functions that can convert variables to JSON strings and
vice-versa. Lets take a look at them.
C R E AT I N G A J S O N S T R I N G F R O M A P H P VA R I A B L E
json_encode() takes a PHP variable and returns a JSON string representing the
variable. Heres our shopping cart example written in PHP:
1 <?php
2
3 $cart = array(
4
5
6
7
8
9
1
0
1
1
array(
1
2
1
3
1
4
1
5
"quantity" => 1
1
6
1
7
),
1
8
array(
1
9
2
0
"productName" => "WonderWidget",
2
1
"quantity" => 3
2
2
2
3
2
4
2
5
),
2
6
2
7
);
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
This produces exactly the same output as our JavaScript example a valid JSON
string representing the variables contents:
Output:
{orderID:12345,shopperName:Faisal
Ahmed,shopperEmail:faisal@gmail.com,contents:
[{"productID":34,"productName":"SuperWidget","quantity":1},
{"productID":56,"productName":"WonderWidget","quantity":3}],orderCompl
eted:true}In a real-world online store, your PHP script would send this JSON
string as part of the Ajax response back to the browser, where the JavaScript
code would use JSON.parse() to turn the string back into a variable so it can
display the carts contents to the shopper.
Note: You can also pass various flags as a second argument to json_encode().
These let you do things like encode certain special characters using hex notation
to make the string more portable, and force empty and indexed arrays to be
encoded as objects (associative arrays). Find out more.
C R E AT I N G A P H P VA R I A B L E F R O M A J S O N S T R I N G
To go the other way and convert a JSON string into a PHP variable, you use
you guessed it json_decode(). Lets rewrite our JavaScript JSON.parse()
example in PHP:
1 <?php
2
3 $jsonString = '
4
5 {
6
7
"orderID": 12345,
8
9
1
0
1
1
1
2
"shopperEmail": "faisal@gmail.com",
"contents": [
1
3
1
4
"productID": 34,
1
5
"productName": "SuperWidget",
1
6
"quantity": 1
1
7
1
8
},
1
9
2
0
"productID": 56,
2
1
"productName": "WonderWidget",
2
2
"quantity": 3
2
3
}
2
4
2
5
],
2
6
2
7
"orderCompleted": true
2
8
2
';
9
3 $cart = json_decode( $jsonString );
0
3
echo $cart->shopperEmail . "<br>";
1
3
2 echo $cart->contents[1]->productName . "<br>";
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
?>
5
4
6
4
7
4
8
4
9
1 </pre>
2 <?php
3
4 class A {
5
6 public $a = 1;
7
8
public $b = 2;
9
1
0
1 function __construct(){
1
1
2 for ( $i=3; $i>0; $i--){
1
3 array_push($this->collection, new B);
1
4
1
5
1 }
6
1
}
7
1
8
1
9
2
0
2
1
2
2
2
3
class B {
2
4
2
5
public $a = 1;
2 public $b = 2;
6
2
7 }
2 echo "<pre>";
8 echo json_encode(new A);
2
9
3
0
3
1
3
2
3
3
3
4
?>
Willgive:
"a":1,
"b":2,
"collection":[{
"a":1,
"b":2
},{
"a":1,
"b":2
},{
"a":1,
"b":2
}]
Step 4:
Now, back in Chrome we load the file (index.php). Thats the array we just
created. If you actually look in developer tools, the script is here under
resources. Its sent it with content type text/html. Technically this isnt really a
problem. It will work, but to be correct it needs to be application/json content
type.
Step 5:
So just back in json.php use the header() function, content-type and then save,
reload. Now if we look here, its application/json and Chrome gives us a warning
here, thats just because we tried to display it as a normal HTML page even
though its not.
Listing 1 The JSON data source (json.php)
1
2 <?php
3
$cities = array(
'Adelaide',
'Perth',
'Melbourne',
'Sydney'
7
8
9
1
0
1
1
);
header('Content-type: application/json');
echo json_encode($cities);
?>
Step 6:
Thats the data source done. Next were going to create some JavaScript to
actually output that. Lets go back here. The script well just update now to load
a select box. Now this doesnt actually do anything, all were going to do is
populate this. So lets call it city, and give it an id of #city-list, so we can refer to
it later in our JavaScript. And well just put a blank element that instructs the
user to select a city. And we save that, and then go back to the index.php script.
Step 7:
Now weve got this dropdown which well populate shortly. Were using jQuery in
this. To make things a little bit simpler were going to use Googles hosted
version of jQuery. We can search Google jQuery and I think its the first link. So
we just click on jQuery and it shows you the versions that they host. You can
either use their loader or just go straight to the path. Well get the minified
version (jquery.min.js) because it loads quicker. We dont need the full source
code.
Step 8:
So lets just load that here. So thats all we need to do to import jQuery into our
script, and were about to create this script.js file, so well just load that one as
well.
The main index file that displays the form (index.php)
1 <html>
2
3
4
5
6
7
8
9
1
<head>
<title>JSON Example - w3programmers.com</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div>
<h1>PHP + jQuery Example - PhpRiot.com</h1>
<select name="city" id="city-list">
0
1
1
<option value="">Select a city...</option>
1
2
1
3
</select>
</div>
</body>
1 </html>
4
1
5
Step 8:
Okay so thats now loading, it doesnt actually do anything yet, but what we can
do is just ensure that jQuery is loaded. So this is the on dom loaded event.
Save that one and go back to the browser. We dont need this any more, now
refresh. Hopefully well get an alert box just to ensure that jQuery is loaded, and
there we go. That means we can keep going.
Step 9:
Now, we go back, we can remove this alert. Now what we want to do is use the
jQuery getJSON() function. So for that, we call $.getJSON(). The script is called
json.php, so put that in, and the callback is the second argument, and when the
callback is called the data returned from the script is passed as the first
argument.
Step 10:
So thats our placeholder. You can have a look at that before we do anything
with it. Just throw in a console.log(), pass the data, save and return the Chrome.
Now if you load developer tools. Lets refresh this page. So now you can see this
script here after the JavaScript is loaded it performed the JSON query. So thats
what we created earlier on but you can this output that we wrote to the console.
So were most of the way there, all we need to do now is use this data to
populate the select box.
Step 11:
So returning to our editor. So we just call $.each(), pass the array as the first
argument and the callback as the second. The first argument to the callback is
the index, so 0, 1, 2, 3 in this case, and the second argument is the value, which
is the name of the city, which is what were going to use.
Step 12:
For each iteration of this loop were going to write a new option to the select
box. So first we need to get the select box. So were going to call it var select,
and we called that #city-list, and then in each iteration option, create the new
option, so we set the value attribute, so when the form is submitted the value is
passed in, and we set the HTML using the .html() function, so we just pass the
city name again. And finally we append it to the select, so appendTo(select).
JavaScript to populate the select box with JSON (script.js)
1
2 jQuery(function($) {
$.getJSON('json.php', function(json) {
$.each(json, function(k, v) {
option.attr('value', v)
.html(v)
.appendTo(select);
});
1
0
1
1
});
});
Final:
Now we can save, return to Chrome, and refresh. Now weve got our developer
tools still open so you can see theyre all appearing here, and in the dropdown.
And thats all there is to it! Now we havent actually done anything with this list,
but you can use this inside your normal forms, or you can trigger the load after a
particular btuton is pressed. Here weve just made it simple and doing it onload,
but you can really do it however you need to.
Combining PHP, JSON, MySQL and jQuery
1.
2.
3.
J S O N - J Q U E RY. J S
1 $(document).ready(function(){
2
3
4
5
$('#getdata-button').live('click', function(){
6
7
$.getJSON('json-data.php', function(data) {
8
9
1
0
1
1
$('#showdata').html("<p>item1="+data.item1+" item2="+data.item2+"
item3="+data.item3+"</p>");
1
1
3
1
4
1
5
});
1
6
});
1
7
1
8
});
1
9
J S O N - D ATA . P H P
1 <?php
2
3 //request data from the database
4
5 //code here to connect to database and get the data you want
6
7 /* Example JSON format
8
9
1
0
1
1
2
1
3
1
4
1 */
5
1
//return in JSON format
6
1
7 echo "{";
1
8
1
9
2 echo "item2: ", json_encode($item2), "\n";
0
2 echo "item3: ", json_encode($item3), "\n";
1
2
2 echo "}";
2
3
2
4
2
5
2
6
2
?>
7
2
8
2
9
3
0
3
1
3
2
3
3
Alternative methods
Create an array in PHP and use the json_encode() function to encode
the whole array.
?
1<?php
2
$arr = array ('item1'=>"I love jquery4u",'item2'=>"You love jQuery4u",'item3'=>"We love
jQuery4u");
3
4
5
echo json_encode($arr);
6
7?>
This will output the array in the correct JSON format; however it may not include
line breaks as the previous example shows so make sure you check this by
alerting the data. There is also a json_decode() function which does the
opposite.
page.html
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
4
5
<head>
6
7
8
9
1
0
1
1
<script src="http://code.jquery.com/jquery-1.5.js"></script>
1
6
1 <div id="showdata"></div>
7
1 </body>
8
1
9
2
0
2
1
2
2 </html>
2
3
2
4
2
5
This entry was posted in Featured Posts, JSON, XML and Web Services and
tagged json by Masud Alam. Bookmark the permalink.