SlideShare una empresa de Scribd logo
1 de 25
SKILLWISE-JSON
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
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
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
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
Json example
<html>
<script type="text/javascript">
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>
<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>
</body>
</html>
•
JSON Object
holding data
JSON
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
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
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
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
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
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
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
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
Json- servlet/jsp interaction
SERVER
JSP
SERVLET
CLIENT
Ajax/J
SON
Request / Response
Request/ Response
JavaScript
JSON
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
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
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
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
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
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
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
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
QUESTIONS
JSON
JSON-(JavaScript Object Notation)

Más contenido relacionado

La actualidad más candente

MongoDB and Ruby on Rails
MongoDB and Ruby on RailsMongoDB and Ruby on Rails
MongoDB and Ruby on Rails
rfischer20
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
Ramamohan Chokkam
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02
Ramamohan Chokkam
 
WebSocket JSON Hackday
WebSocket JSON HackdayWebSocket JSON Hackday
WebSocket JSON Hackday
Somay Nakhal
 
Building Your First App: An Introduction to MongoDB
Building Your First App: An Introduction to MongoDBBuilding Your First App: An Introduction to MongoDB
Building Your First App: An Introduction to MongoDB
MongoDB
 
Mongoid in the real world
Mongoid in the real worldMongoid in the real world
Mongoid in the real world
Kevin Faustino
 

La actualidad más candente (20)

Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examples
 
An Introduction to JSON JavaScript Object Notation
An Introduction to JSON JavaScript Object NotationAn Introduction to JSON JavaScript Object Notation
An Introduction to JSON JavaScript Object Notation
 
J s-o-n-120219575328402-3
J s-o-n-120219575328402-3J s-o-n-120219575328402-3
J s-o-n-120219575328402-3
 
MongoDB and Ruby on Rails
MongoDB and Ruby on RailsMongoDB and Ruby on Rails
MongoDB and Ruby on Rails
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
Javascript2839
Javascript2839Javascript2839
Javascript2839
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
 
Advanced Json
Advanced JsonAdvanced Json
Advanced Json
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02
 
AJAX
AJAXAJAX
AJAX
 
Json Tutorial
Json TutorialJson Tutorial
Json Tutorial
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
 
Json - ideal for data interchange
Json - ideal for data interchangeJson - ideal for data interchange
Json - ideal for data interchange
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDB
 
WebSocket JSON Hackday
WebSocket JSON HackdayWebSocket JSON Hackday
WebSocket JSON Hackday
 
Mongo Nosql CRUD Operations
Mongo Nosql CRUD OperationsMongo Nosql CRUD Operations
Mongo Nosql CRUD Operations
 
Building Your First App: An Introduction to MongoDB
Building Your First App: An Introduction to MongoDBBuilding Your First App: An Introduction to MongoDB
Building Your First App: An Introduction to MongoDB
 
Json vs Gson vs Jackson
Json vs Gson vs JacksonJson vs Gson vs Jackson
Json vs Gson vs Jackson
 
Mongoid in the real world
Mongoid in the real worldMongoid in the real world
Mongoid in the real world
 
Building your first app with mongo db
Building your first app with mongo dbBuilding your first app with mongo db
Building your first app with mongo db
 

Destacado (10)

Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1
 
Hibernate
HibernateHibernate
Hibernate
 
Introduction to AJAX and DWR
Introduction to AJAX and DWRIntroduction to AJAX and DWR
Introduction to AJAX and DWR
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservices
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
Json
JsonJson
Json
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 

Similar a JSON-(JavaScript Object Notation)

JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)
Raghu nath
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
HemaSenthil5
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
titanlambda
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)
Faysal Shaarani (MBA)
 
json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
AmitSharma397241
 

Similar a JSON-(JavaScript Object Notation) (20)

Json
JsonJson
Json
 
Json
JsonJson
Json
 
Hands on JSON
Hands on JSONHands on JSON
Hands on JSON
 
JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptx
 
JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)
 
java script json
java script jsonjava script json
java script json
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
 
Json
JsonJson
Json
 
CSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptxCSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptx
 
JSON
JSONJSON
JSON
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
 
Xml And JSON Java
Xml And JSON JavaXml And JSON Java
Xml And JSON Java
 
JSON(JavaScript Object Notation) Presentation transcript
JSON(JavaScript Object Notation) Presentation transcriptJSON(JavaScript Object Notation) Presentation transcript
JSON(JavaScript Object Notation) Presentation transcript
 
JSON_FIles-Py (2).pptx
JSON_FIles-Py (2).pptxJSON_FIles-Py (2).pptx
JSON_FIles-Py (2).pptx
 
Working with JSON
Working with JSONWorking with JSON
Working with JSON
 
BITM3730Week8.pptx
BITM3730Week8.pptxBITM3730Week8.pptx
BITM3730Week8.pptx
 
Json
JsonJson
Json
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)
 
json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
 
JSON.pptx
JSON.pptxJSON.pptx
JSON.pptx
 

Más de Skillwise Group

Más de Skillwise Group (20)

Skillwise Consulting New updated
Skillwise Consulting New updatedSkillwise Consulting New updated
Skillwise Consulting New updated
 
Email Etiquette
Email Etiquette Email Etiquette
Email Etiquette
 
Healthcare profile
Healthcare profileHealthcare profile
Healthcare profile
 
Manufacturing courses
Manufacturing coursesManufacturing courses
Manufacturing courses
 
Retailing & logistics profile
Retailing & logistics profileRetailing & logistics profile
Retailing & logistics profile
 
Skillwise orientation
Skillwise orientationSkillwise orientation
Skillwise orientation
 
Overview- Skillwise Consulting
Overview- Skillwise Consulting Overview- Skillwise Consulting
Overview- Skillwise Consulting
 
Skillwise corporate presentation
Skillwise corporate presentationSkillwise corporate presentation
Skillwise corporate presentation
 
Skillwise Profile
Skillwise ProfileSkillwise Profile
Skillwise Profile
 
Skillwise Softskill Training Workshop
Skillwise Softskill Training WorkshopSkillwise Softskill Training Workshop
Skillwise Softskill Training Workshop
 
Skillwise Insurance profile
Skillwise Insurance profileSkillwise Insurance profile
Skillwise Insurance profile
 
Skillwise Train and Hire Services
Skillwise Train and Hire ServicesSkillwise Train and Hire Services
Skillwise Train and Hire Services
 
Skillwise Digital Technology
Skillwise Digital Technology Skillwise Digital Technology
Skillwise Digital Technology
 
Skillwise Boot Camp Training
Skillwise Boot Camp TrainingSkillwise Boot Camp Training
Skillwise Boot Camp Training
 
Skillwise Academy Profile
Skillwise Academy ProfileSkillwise Academy Profile
Skillwise Academy Profile
 
Skillwise Overview
Skillwise OverviewSkillwise Overview
Skillwise Overview
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPT
 
Skillwise - Business writing
Skillwise - Business writing Skillwise - Business writing
Skillwise - Business writing
 
Imc.ppt
Imc.pptImc.ppt
Imc.ppt
 
Skillwise cics part 1
Skillwise cics part 1Skillwise cics part 1
Skillwise cics part 1
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

JSON-(JavaScript Object Notation)

  • 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
  • 6. Json example <html> <script type="text/javascript"> 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> <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> </body> </html> • JSON Object holding data 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