JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and for machines to parse and generate. It is built on two structures: a collection of name/value pairs and an ordered list of values. JSON is primarily used to transmit data between a server and web application, providing an alternative to XML. It can represent numbers, strings, ordered sequences of values (arrays), and collections of name/value pairs (objects).
2. What is JSON ?
• Stands for JavaScript Object Notation
• Lightweight text data interchange format
• Language independent
• Self describing and easy to understand
• Uses JavaScript Syntax for describing data Objects
• It’s a language and platform independent
• JSON parsers and JSON libraries exist for many different
programming languages
JSON
3. Much like xml
• JSON is plain Text
• JSON is self describing
• JSON is hierarchical (values within values)
• JSON can be parsed by JAVASCRIPT
• JSON data can be transported using AJAX
JSON
4. MUCH UNLIKE XML
• No End Tag
• Shorter
• Quicker to read and write
• Can be parsed using built-in JavaScript eval()
• Uses arrays
• No Reserve Words
JSON
5. WHY JSON ?
• For AJAX application, JSON is faster and
easier then XML :
• Using XML
1. Fetch the XML document
2. Use DOM to loop through the document
3. Extract values and store in variables
• Using JSON
1. Fetch a JSON STRING
2. eval() the JSON String
JSON
7. JSON SYNTAX
JSON syntax is a subset of JavaScript
Syntax
• Data is in Name/Value Pairs
• Data is separated by commas.
• Curly brackets hold Objects
• Square brackets hold arrays
JSON
8. Json name/value pairs
• JSON data is written in name/value pairs
A name/value pair consists of a field name (in double quotes), followed
by a colon, followed by a value:
“firstname” : “John”
• This is simple to understand, and equals to the JavaScript statement:
firstName = "John"
JSON
9. Json values
• JSON values can be
1. A number (Integer or Floating Point)
2. A String (in Double Quotes)
3. A Boolean (True or False)
4. An Array in Square [] Brackets
5. An Object in Curly { } brackets
6. NULL
JSON
10. JSON OBJECTS
JSON objects are written using curly brackets.
Object can contain multiple name/value pairs.
{“firstname”: “John”, “lastname” : “Smith”}
This is also simple. It is equals to the JavaScript elements :
firstname=“John”
lastname= “Smith”
JSON
11. Json arrays
• JSON arrays are written inside square brackets.
• An array can contain multiple objects:
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:
employees[0].lastName;
JSON
12. Json files
• The file type for JSON files is ".json"
• The MIME type for JSON text is "application/json"
• Character Encoding
1. Strictly UNICODE
2. Default: utf-8
3. Utf-16 and utf-32 are allowed
JSON
13. Converting a json text to a javascript object
• One of the most common use of JSON is to fetch JSON data from a web
server (as a file or as an HttpRequest), convert the JSON data to a
JavaScript object, and then use the data in a web page.
• For simplicity, this can be demonstrated by using a string as input
(instead of a file).
var txt = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
• Since JSON syntax is a subset of JavaScript syntax, the JavaScript
function eval() can be used to convert a JSON text into a JavaScript
object.
• The eval() function uses the JavaScript compiler which will parse the
JSON text and produce a JavaScript object. The text must be wrapped in
parenthesis to avoid a syntax error:
var obj = eval ("(" + txt + ")");
JSON
14. Example: convert json data to javascript object
<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 type="text/javascript">
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
var obj = eval ("(" + txt + ")");
document.getElementById("fname").innerHTML=obj.employees[1].firstName
document.getElementById("lname").innerHTML=obj.employees[1].lastName
</script>
</body>
</html>
JSON data in the
form of String
Eval() function to parse the
JSON test
JSON
16. JSON and JAVA
Now in this part you will study how to use JSON in Java.
• To have functionality of JSON in java you must have JSON-lib. JSON-
lib also requires following "JAR" files:
• commons-lang.jar
• commons-beanutils.jar
• commons-collections.jar
• commons-logging.jar
• ezmorph.jar
• json-lib-2.2.2-jdk15.jar
* Copy these Jar files into the .lib folder of your web application.
JSON
17. Understanding the JsonObject
class
A JSONObject is an unordered collection of name/value pairs. Its external form is a
String wrapped in curly braces with colons between the names and values, and
commas between the values and names.
The ‘put’ method adds or replace values in an Object. Consider the example given
below:
String myString = new JSONObject(). put (“JSON”,”Hello, World”).toString();
The above expression will produce the String :
{“JSON” : “Hello, World” }
This is exactly how we want it in JavaScript for further processing.
JSON
18. Understaning jsonarray class
• The JSONArray can hold Several JSON
Object in the format that we require in
the Client Side.
• Ajax will transfer this back to the
JavaScript in the Client Code where this
pattern which is in string form can be
easily parsed using eval() or parse()
functions.
JSON
19. JSON-SERVLET EXAMPLE
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
public class JSONServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
JSONArray empArray=new JSONArray();
JSONObject empObject = new JSONObject();
empObject.put(“Name”, “Allen”);
empArray.add(empObject);
out.println(empArray);
}
}
}
** Similarly multiple JSON Objects can be added to the JSON Array
** The Above Data will be available in the Client side as :
[ {“Name”:”Allen”}] -> Single Object inside a JSON Array
Ajax will invoke this SERVLET
residing in the Server
This data is send to the
Client and there the
JavaScript can use JSON’s
eval() function for
process this data
JSON
20. JSON PARSER
• The eval() function can compile and execute any JavaScript.This
represents a potential security problem.
• 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.
JSON
21. JSON PARSER EXAMPLE
<html>
<body>
<h2>Create Object from JSON String</h3>
<p>
First Name: <span id="fname"></span><br />
Last Name: <span id="lname"></span><br />
</p>
<script type="text/javascript">
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(txt);
document.getElementById("fname").innerHTML=obj.employees[1].firstName
document.getElementById("lname").innerHTML=obj.employees[1].lastName
</script>
</body>
</html>
Parser at Work
JSON
22. JSON PARSER EXAMPLE
<html>
<body>
<h2>Create Object from JSON String</h3>
<p>
First Name: <span id="fname"></span><br />
Last Name: <span id="lname"></span><br />
</p>
<script type="text/javascript">
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(txt);
document.getElementById("fname").innerHTML=obj.employees[1].firstName
document.getElementById("lname").innerHTML=obj.employees[1].lastName
</script>
</body>
</html>
Parser at Work
JSON
23. JSON - CONCLUSION
• JSON or JavaScript Object Notation, is a lightweight text-based open standard
designed for human readable data interchange. It is derived from the JavaScript
scripting language for representing simple data structures and associative arrays,
called objects. Despite its relationship to JavaScript, it is language-independent,
with parsers available for most languages.
• The JSON format was originally specified by Douglas Crockford, and is described
in RFC 4627. The official Internet media type for JSON is application/json. The
JSON filename extension is .json.
• The JSON format is often used for serializing and transmitting structured
data over a network connection. It is used primarily to transmit data
between a server and web application, serving as an alternative to XML.
JSON