Chapter 3: JSON- JavaScript Object Notation
What is JSON
o JSON stands for JavaScript Object Notation.
o JSON is a text format for storing and transporting data
o JSON is an open standard data-interchange format.
o JSON is lightweight and self-describing.
o JSON originated from JavaScript.
o JSON is easy to read and write.
o JSON is language independent.
o JSON supports data structures such as arrays and objects.
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.
JSON Example
File: [Link]
{"employees":[
{"name":"Sonoo", "email":"sonoojaiswal1987@[Link]"},
{"name":"Rahul", "email":"rahul32@[Link]"},
{"name":"John", "email":"john32bob@[Link]"} ]
}
Features of JSON
o Simplicity
o Openness
o Self-Describing
o Internationalization
o Extensibility
o Interoperability
Following are the advantages of JSON:
Less Verbose: In contrast to XML, JSON follows a compact style to improve
its users' readability. While working with a complex system, JSON tends to
make substantial enhancements.
Faster: The JSON parsing process is faster than that of the XML because the
DOM manipulation library in XML requires extra memory for handling large
XML files. However, JSON requires less data that ultimately results in reducing
the cost and increasing the parsing speed.
Readable: The JSON structure is easily readable and straightforward.
Regardless of the programming language that you are using, you can easily map
the domain objects.
Structured Data: In JSON, a map data structure is used, whereas XML follows
a tree structure. The key-value pairs limit the task but facilitate the predictive
and easily understandable model.
Why Use JSON?
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:
[Link]()
JavaScript also has a built in function for converting an object into a JSON string:
[Link]()
Used to receive pure text from a server and use it as a JavaScript object.
Used to send a JavaScript object to a server in pure text format.
Used to work with data as JavaScript objects, with no complicated parsing and
translations.
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 names require double quotes.
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
1. JSON Strings
Strings in JSON must be written in double quotes.
E.g : {"name":"John"}
2. JSON Numbers
Numbers in JSON must be an integer or a floating point.
E.g:{"age":30}
1. JSON Objects
Values in JSON can be objects.
{
"employee":{"name":"John", "age":30, "city":"New York"}
}
Objects as values in JSON must follow the JSON syntax.
2. JSON Arrays
Values in JSON can be arrays.
{
"employees":["John", "Anna", "Peter"]
}
3. JSON Booleans
Values in JSON can be true/false.
{"sale":true}
6 JSON null
Values in JSON can be null.
{"middlename":null}
The JSON syntax is a subset of the JavaScript syntax.
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
[Link];
It can also be accessed like this:
Example
// returns John
person["name"];
Data can be modified like this:
Example
[Link] = "Gilbert";
It can also be modified like this:
Example
person["name"] = "Gilbert"
<html>
<body>
<h2>Access a JavaScript object</h2>
<p id="demo"></p>
<script>
const myObj = {name:"John", age:30, city:"New York"};
[Link]("demo").innerHTML =
[Link];
</script>
</body>
</html>
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 employee’s 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.
Similarities between the json and XML.
o Self-describing: Both json and xml are self-describing as both xml data and
json data are human-readable text.
o Hierarchical: Both json and xml support hierarchical structure. Here
hierarchical means that the values within values.
o Data interchange format: JSON and XML can be used as data interchange
formats by many different programming languages.
o Parse: Both the formats can be easily parsed.
o Retrieve: Both formats can be retrieved by using HTTP requests. The
methods used for retrieving the data are GET, PUT, POST.
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.
Why JSON is Better Than XML
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
[Link] the JSON string
Difference between JSON and XML
The following are the differences between the json and xml:
JSON XML
JSON stands for javascript object XML stands for an extensible markup language.
notation.
The extension of json file is .json. The extension of xml file is .xml.
The internet media type is The internet media type is application/xml or text/xm
application/json.
The type of format in JSON is data The type of format in XML is a markup language.
interchange.
It is extended from javascript. It is extended from SGML.
It is open source means that we do not It is also open source.
have to pay anything to use JSON.
The object created in JSON has some XML data does not have any type.
type.
The data types supported by JSON are XML data is in a string format.
strings, numbers, Booleans, null, array.
It does not have any capacity to display XML is a markup language, so it has the capac
the data. display the content.
JSON has no tags. XML data is represented in tags, i.e., start tag and en
XML file is larger. If we want to represent the d
XML then it would create a larger file as compa
JSON.
JSON is quicker to read and write. XML file takes time to read and write becau
learning curve is higher.
JSON can use arrays to represent the XML does not contain the concept of arrays.
data.
It can be parsed by a standard javascript XML data which is used to interchange the data, m
function. It has to be parsed before use. parsed with respective to their programming langu
use that.
It can be easily parsed and little bit code It is difficult to parse.
is required to parse the data.
File size is smaller as compared to XML. File size is larger.
JSON is data-oriented. XML is document-oriented.
It is less secure than XML. It is more secure than JSON.
[Link]()
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 [Link](), and the data becomes a JavaScript object.
Example - Parsing JSON
Imagine we received this text from a web server:
'{"name":"abc", "age":30, "city":"india"}'
Use the JavaScript function [Link]() to convert text into a JavaScript object:
const obj = [Link]('{"name":"abc", "age":30, "city":"india"}');
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>
[Link]("demo").innerHTML = [Link];
</script>
Array as JSON
When using the [Link]() 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 = [Link](text);
[Link]()
A common use of JSON is to exchange data to/from a web server. When sending
data to a web server, the data has to be a string. Convert a JavaScript object into a
string with [Link]().
Stringify a JavaScript Object we have this object in JavaScript:
const obj = {name: "abc", age: 30, city: "India"};
Use the JavaScript function [Link]() to convert it into a string.
const myJSON = [Link](obj);
The result will be a string following the JSON notation.
myJSON is now a string, and ready to be sent to a server:
Example
const obj = {name: "abc", age: 30, city: "India"};
const myJSON = [Link](obj);
You will learn how to send JSON to a server in the next chapters.
Stringify a JavaScript Array
It is also possible to stringify JavaScript arrays:
Imagine we have this array in JavaScript:
const arr = ["John", "Peter", "Sally", "Jane"];
Use the JavaScript function [Link]() to convert it into a string.
const myJSON = [Link](arr);
The result will be a string following the JSON notation.
myJSON is now a string, and ready to be sent to a server:
Example
const arr = ["John", "Peter", "Sally", "Jane"];
const myJSON = [Link](arr);
JSON Comments
JSON doesn't support comments. It is not a standard.
But you can do some tricks such as adding extra attribute for comment in JSON
object, for example:
{
"employee": {
"name": "Bob",
"salary": 56000,
"comments": "Hello good morning"
}
}
Here, "comments" attribute can be treated as comment.