JSON
JSON stands for JavaScript Object Notation
JSON is a lightweight data-interchange format
JSON is plain text written in JavaScript object notation
JSON is used to send data between computers
JSON is language independent *
The JSON syntax is derived from JavaScript object notation, but the JSON format is text only.
Code for reading and generating JSON exists in many programming languages.
The JSON format was originally specified by Douglas Crockford.
The JSON format is syntactically similar to the code for creating JavaScript objects. Because of this, a
JavaScript program can easily convert JSON data into JavaScript objects.
Since the format is text only, JSON data can easily be sent between computers, and used by any
programming language.
JavaScript has a built in function for converting JSON strings into JavaScript objects:
JSON.parse()
JavaScript also has a built in function for converting an object into a JSON string:
JSON.stringify()
Storing Data
When storing data, the data has to be a certain format, and regardless of where you choose to store
it, text is always one of the legal formats.
JSON makes it possible to store JavaScript objects as text.
JSON Syntax
The JSON syntax is a subset of the JavaScript syntax.
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
JSON Data - A Name and a Value
JSON data is written as name/value pairs (aka key/value pairs).
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a
value:
Example
"name":"John"
JSON - Evaluates to JavaScript Objects
The JSON format is almost identical to JavaScript objects.
In JSON, keys must be strings, written with double quotes:
JSON
{"name":"John"}
In JavaScript, keys can be strings, numbers, or identifier names:
JavaScript
{name:"John"}
JSON Values
In JSON, values must be one of the following data types:
a string
a number
an object
an array
a boolean
null
In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:
a function
a date
undefined
In JSON, string values must be written with double quotes:
JSON
{"name":"John"}
In JavaScript, you can write string values with double or single quotes:
JavaScript
{name:'John'}
JavaScript Objects
Because JSON syntax is derived from JavaScript object notation, very little extra software is needed
to work with JSON within JavaScript.
With JavaScript you can create an object and assign data to it, like this:
Example
person = {name:"John", age:31, city:"New York"};
You can access a JavaScript object like this:
Example
// returns John
person.name;
It can also be accessed like this:
Example
// returns John
person["name"];
Data can be modified like this:
Example
person.name = "Gilbert";
It can also be modified like this:
Example
person["name"] = "Gilbert";
JSON vs XML
Both JSON and XML can be used to receive data from a web server.
The following JSON and XML examples both define an employees object, with an array of 3
employees:
JSON Example
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}
XML Example
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>
JSON is Like XML Because
Both JSON and XML are "self describing" (human readable)
Both JSON and XML are hierarchical (values within values)
Both JSON and XML can be parsed and used by lots of programming languages
Both JSON and XML can be fetched with an XMLHttpRequest
JSON is Unlike XML Because
JSON doesn't use end tag
JSON is shorter
JSON is quicker to read and write
JSON can use arrays
The biggest difference is:
XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.
XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.
For AJAX applications, JSON is faster and easier than XML:
Using XML
Fetch an XML document
Use the XML DOM to loop through the document
Extract values and store in variables
Using JSON
Fetch a JSON string
JSON.Parse the JSON string
What are the uses of JSON?
JSON is used when writing javascript based application which incudes browser extension and
websites.
JSON, data exchange format is used for serializing and transmitting structured data above
network connection.
This is mainly used to transmit data between server and web application.
Web services and APIs use JSON format to offer public data.
JSON can be used with modern programming languages.
JSON Data Types
Valid Data Types
In JSON, values must be one of the following data types:
a string
a number
an object (JSON object)
an array
a boolean
null
JSON values cannot be one of the following data types:
a function
a date
undefined
JSON Strings
Strings in JSON must be written in double quotes.
Example
{"name":"John"}
JSON Numbers
Numbers in JSON must be an integer or a floating point.
Example
{"age":30}
JSON Objects
Values in JSON can be objects.
Example
{
"employee":{"name":"John", "age":30, "city":"New York"}
}
Objects as values in JSON must follow the JSON syntax.
JSON Arrays
Values in JSON can be arrays.
Example
{
"employees":["John", "Anna", "Peter"]
}
JSON Booleans
Values in JSON can be true/false.
Example
{"sale":true}
JSON null
Values in JSON can be null.
Example
{"middlename":null}
JSON.parse()
A common use of JSON is to exchange data to/from a web server.
When receiving data from a web server, the data is always a string.
Parse the data with JSON.parse(), and the data becomes a JavaScript object.
Example - Parsing JSON
Imagine we received this text from a web server:
'{"name":"John", "age":30, "city":"New York"}'
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
Make sure the text is in JSON format, or else you will get a syntax error.
Use the JavaScript object in your page:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = obj.name;
</script>
Array as JSON
When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript
array, instead of a JavaScript object.
Example
const text = '["Ford", "BMW", "Audi", "Fiat"]';
const myArr = JSON.parse(text);
JavaScript Objects
You can create a JavaScript object from a JSON object literal:
Example
myObj = {"name":"John", "age":30, "car":null};
Normally, you create a JavaScript object by parsing a JSON string:
Example
myJSON = '{"name":"John", "age":30, "car":null}';
myObj = JSON.parse(myJSON);
Accessing Object Values
You can access object values by using dot (.) notation:
Example
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
x = myObj.name;
You can also access object values by using bracket ([]) notation:
Example
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
x = myObj["name"];
Looping an Object
You can loop through object properties with a for-in loop:
Example
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += x + ", ";
}
In a for-in loop, use the bracket notation to access the property values:
Example
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += myObj[x] + ", ";
}
Arrays in JSON are almost the same as arrays in JavaScript.
In JSON, array values must be of type string, number, object, array, boolean or null.
In JavaScript, array values can be all of the above, plus any other valid JavaScript expression,
including functions, dates, and undefined.
JavaScript Arrays
You can create a JavaScript array from a literal:
Example
myArray = ["Ford", "BMW", "Fiat"];
You can create a JavaScript array by parsing a JSON string:
Example
myJSON = '["Ford", "BMW", "Fiat"]';
myArray = JSON.Parse(myJSON);
Accessing Array Values
You access array values by index:
Example
myArray[0];
Arrays in Objects
Objects can contain arrays:
Example
{
"name":"John",
"age":30,
"cars":["Ford", "BMW", "Fiat"]
}
You access array values by index:
Example
myObj.cars[0];
Looping Through an Array
You can access array values by using a for in loop:
Example
for (let i in myObj.cars) {
x += myObj.cars[i];
}
Or you can use a for loop:
Example
for (let i = 0; i < myObj.cars.length; i++) {
x += myObj.cars[i];
}
Parsing JSON and XML
JSON Parser
The eval() function can compile and execute any javascript. This represent a potential security
problem.
It is safer to use a JSON parser to convert a JSON text to a javascript object. A JSON parser identifies
only JSON text and does not compile scripts.
In browsers that provide native JSON hold, JSON parsers are faster.
Native JSON support is integrated in newer browsers and in the newest ECMAScript (javascript)
standard.
Parsing JSON HttpResponse
If we get HttpResponse as JSON format, then we require to parse it.
The following steps are used to parse JSON.
Get the content from HttpResponse
HttpEntity he=httpResponse.getEntity();
InputStream is=he.getContent();
Read the content stored into JSON object
Parsing XML HttpResponse
If we get the HttpResponse as XML format, then we require to parse it. The following fragment is
used to parse the XML.
Get the content from HttpResponse
HttpEntity he=httpResponse.getEntity();
String xml=EntityUtils.toString(he);
Convert the response data to document object
DocumentBuilderFactory dbf=DocumentBuilderFactory.newinstance();
DocumentBuilder db=dbf.newDocumentBuilder();
InputSource is=new InputSource();
Document doc=db.parse(is);
Get element from document object
NodeList nl=doc.getElementsByTagName();
for(i=0;i<nl.getLength();i++)
Element e=nl.item(i);