JavaScript Object Notation
JSON
What is JSON?
● JSON stands for JavaScript Object Notation.
● JSON is a lightweight data-interchange format.
● JSON is a plain text written in JavaScript object notation.
● JSON is a language independent.
● JSON is a text-based data format that is used to store and transfer
data.
● It is a standard text-based format for represent structured data based
on JavaScript object syntax and commonly used for transmitting data in
web applications.
● For example: sending some data from the server to the client, so it can
be displayed on a web page, or vice versa.
JSON Example
● This example is a JSON string:
‘ {“name”:”John”, “age”:30, “car”:null}
’
● It defines an object with 3 properties: name, age, car.
● Each property has a value.
● If we parse the JSON string with a JavaScript program, we can
access the data as an object:
let personName = obj.name;
let personAge = obj.age;
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 language.
● JS has a built in function for converting JSON strings into JS objects:
JSON.parse( )
● JS also has a built in function for converting an object into a JSON
string:
JSON.stringify( )
● Pure text from a server can be received and used as a JavaScript
object.
● JavaScript objects also can be sent to a server in pure text format.
● You can work with data as JS objects, with no complicated parsing
and translations.
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 JS objects as text.
JSON Syntax
● The JSON syntax is a subset of the JavaScript syntax.
● JSON syntax rules:
○ 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:
“name”:“Hakim”
● JSON names/keys require double quotes, not as in JavaScript.
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 JS values can be all of the above, plus any other valid JS
expression including:
○ a function
○ a date
○ undefined
● String values in JSON - use double quotes:
“name”:“Hakim”
● String values in JS - double or single quotes:
Name: ‘Hakim’
JavaScript Arrays as JSON
● The same way JS objects can be written as JSON, JS arrays can also
be written as JSON.
JSON Files
● The file type for JSON files is .json
● The MIME type for JSON text is “application/json”
JSON Data Types
{ “name”:“Hakim”
● JSON Strings: written in double quotes
}
● JSON Numbers: must be integer or a floating { “age”:25 }
point
● JSON Objects: values in JSON can be objects
{
“employee”:{ “name”: “Hakim”, “age”: 30, “city”:
“Bangi”}
}
● JSON Arrays: values in JSON can be arrays
{
“employee”:[ “Hakim”, “Rafiq”, “Khadeeja”]
}
JSON Data Types
{ “sale”: true }
● JSON Booleans: values can be true/false
{ “middlename”:null }
● JSON null: values can be 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 JS object
● Example - Parsing JSON
○ Imagine we received this text from a web server:
‘ { “name”: “Hakim”, “age”: 30, “city”: “Bangi”} ’
○ Use the JS function JSON.parse() to convert text into a JS object:
const obj = JSON.parse(‘ { “name”: “Hakim”, “age”: 30, “city”:
“Bangi”} ’);
● Use the JS object in your page:
* make sure the text is in JSON format, or
else you will get a syntax error.
Array as JSON
● When using the JSON.parse() on a JSON derived from an array, the
method will return a JS array, instead of a JS object.
Exceptions - Parsing Dates
● Date objects are not allowed in JSON
● If need to include date, write it as a string. Then convert it back into
a date object later.
Exception - Parsing Functions
● Functions are not allowed in JSON.
● If need to include a function, write it as a string. Then convert it
back into a function later.
*avoid using functions in JSON as they will lose their scope and we have to use
eval() to convert them back into functions.
JSON.stringify()
● 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.
● JS object can be converted into a string with JSON.stringify().
Stringify a JavaScript Object
● Let say we have this object in JavaScript:
const obj = { name: “Hakim”, age: 30, city:
“Bangi” } ;
● Use the JavaScript function JSON.stringify() to convert it into a
string.
const myJSON = JSON.stringify(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
Stringify a JavaScript Array
● It is also possible to stringify JS arrays.
● Let say we have this array in JavaScript.
const arr = [“Hakim”, “Rafiq”,
“Khadeeja”] ;
● Use the JS function JSON.stringify() to convert it into a string.
const myJSON = JSON.stringify(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
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.
Example
Exceptions - Stringify Dates
● In JSON, date objects are not allowed. The JSON.stringify()
function will convert any dates into strings.
*the string can be convert back into a date
object at the receiver
Exceptions - Stringify Functions
● In JSOn, functions are not allowed as object values.
● . The JSON.stringify() function will remove any functions form JS
object, both the key and the value
Example
● This can be omitted if you convert your functions into string before
running the JSON.stringify() function.
● Sending functions using JSON will lose their scope and the receiver
would have to use eval() to convert them back into functions.
Accessing Object Values
● Object values can be accessed by using dot (.) notation:
● Example:
const myJSON = ‘ { “name”:“Hakim”, “age”:25, “car”:null} ’;
Const myObj = JSON.parse(myJSON);
x =myObj.name;
● Object values also can be accessed using bracket ([ ]) notation:
const myJSON = ‘ { “name”:“Hakim”, “age”:25, “car”:null} ’;
Const myObj = JSON.parse(myJSON);
x =myObj.[“name”];
Looping an Object
● Loop through object properties using for-in loop:
const myJSON = ‘ { “name”:“Hakim”, “age”:25, “car”:null} ’;
Const myObj = JSON.parse(myJSON);
let text = “”;
for(const x in myObj){
text += x + “, ”;
}
Looping an Object
● In a for-in loop, use the bracket notation to access the property
values:
const myJSON = ‘ { “name”:“Hakim”, “age”:25, “car”:null} ’;
Const myObj = JSON.parse(myJSON);
let text = “”;
for(const x in myObj){
text += myObj[x] + “, ”;
}
Accessing Array Values
● Array values can be accessed by index:
myArray[0];
● Example:
{
“name”:“Hakim”,
“age”:25,
“car”:[“Ford”, “BMW”, “”Fiat”]
}
● Array values can be accessed by index:
myObj.cars[0];
Looping Through an Array
● Array values can be accessed by using a for-in loop:
● Example:
let text = “”;
for(let i in myObj.cars){
text += myObj.cars[i] + “, ”;
}
● Or by using a for loop:
let text = “”;
for(let i = 0; i< myObj.cars.lenght; i++){
text += myObj.cars[i] + “, ”;
}
FETCH API
What is Fetch API
● The Fetch API provides a JavaScript interface for accessing
and manipulating parts of the HTTP pipeline, such as
requests and responses. It also provides a global fetch() method
that provides an easy, logical way to fetch resources
asynchronously across the network.
Introduction of JS Fetch API
● The Fetch API is a modern interface that allows you to make HTTP
requests to servers from web browsers.
● The Fetch API uses the Promise to deliver more flexible features to
make requests to servers from the web browsers.
● The fetch() method is available in the global scope that instructs the
web browsers to send a request to a URL.
Sending a Request
● The fetch() requires only one parameter which is the URL of the
resource that you want to fetch:
● The fetch() method returns a Promise so you can use the then() and
catch() methods to handle it:
● When the request completes, the resource is available. At this time,
the promise will resolve into a Response object.
● The Response object is the API wrapper for the fetched resource. The
Response object has a number of useful properties and methods to
inspect the response.
Reading the Response
● If the contents of the response are in the raw text format, you can
use the text() method. The text() method returns a Promise that
resolves with the complete contents of the fetched resource:
● In practice, you often use the async/await with the fetch() method
like this:
JavaScript Fetch API example
● Suppose that you have a json ● The following shows the HTML
file that locates on the page:
webserver with the following
contents:
● In the app.js, we’ll use the fetch() method to get the user data
and render the data inside the <div> element with the class
container.
● First, declare the getUsers() function that fetches users.json from
the server.
● Then, develop the renderUsers() function that renders user data: