100% found this document useful (1 vote)
32 views27 pages

IP Lecture 18 JSON

Uploaded by

kananiparth04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
32 views27 pages

IP Lecture 18 JSON

Uploaded by

kananiparth04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

JSON

Content
• Introduction
• Why to use JSON?
• JSON Syntax Rules
• JSON.parse
• JSON.stringify
Introduction
• JSON stands for JavaScript Object Notation
o A text format for storing and transporting data

o "self-describing" and easy to understand

o Lightweight data-interchange format

• Plain text written in JavaScript object notation


• Used to send data between computers
• Language independent
Introduction
Example:

'{"name":"John", "age":30, "car":null}'

It defines an object with 3 properties: name, age, car

Each property has a value.

If you parse the JSON string with a JavaScript program, you can access the
data as an object:

let personName = obj.name;

let personAge = obj.age;


Why to use JSON
• The JSON format is syntactically similar to the code for creating JavaScript
objects.
• So, a JavaScript program can easily convert JSON data into JavaScript objects.
• JSON data can easily be sent between computers, and used by any
programming language.
o Since the format is text only

Built-in functions:
• JSON.parse(): For converting JSON strings into JavaScript objects

• JSON.stringify(): For converting an object into a JSON string


Why to use JSON
• Receive pure text from a server and use it as a JavaScript object.
• Send a JavaScript object to a server in pure text format.
• Work with data as JavaScript objects, with no complicated parsing and
translations.
• When storing data, the data has to be a certain format: text is always
one of the legal formats.
• JSON makes it possible to store JavaScript objects as text.
JSON Syntax Rules
The JSON syntax is a subset of the JavaScript syntax.
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

The file type for JSON files is ".json"


The MIME type for JSON text is "application/json"
JSON Syntax Rules
JSON Data - A Name and a Value

• JSON data is written as name/value pairs (key/value pairs).


• A name/value pair consists of a field name (in double quotes),
followed by a colon, followed by a value
• JSON names require double quotes.

Example
"name":"John"
JSON Syntax Rules
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 Example:
{"name":"John"}

In JavaScript, keys can be strings, numbers, or identifier names:


JavaScript Example:
{name:"John"}
JSON Syntax Rules
JSON Values

JSON values must be one of the following data types:


• String: Strings in JSON must be written in double quotes.

{"name":"John"}

• Number: Numbers in JSON must be an integer or a floating point.

{"age":30}

• an object: Values in JSON can be objects.

"employee":{"name":"John", "age":30, "city":"New York"}

}
JSON Syntax Rules
JSON Values

• an array: Values in JSON can be arrays.

"employees":["John", "Anna", "Peter"]

• Boolean: Values in JSON can be true/false.

{"sale":true}

• Null: Values in JSON can be null.

{"middlename":null}
JSON Syntax Rules
JSON Values

JSON values cannot be one of the following data types:


• a function
• a date
• undefined
JSON.parse
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.

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


JSON.parse( )
<!DOCTYPE html>
<html>
<body>

<h2>Creating an Object from a JSON String</h2>

<p id="demo"></p>

<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " +
obj.age;
</script>

</body>
</html>
Arrays as JSON
<!DOCTYPE html>
<html> • When using the JSON.parse()
<body> on a JSON derived from an
<h2>Parsing a JSON Array.</h2> array, the method will return
<p>Data written as an JSON array will be parsed into a
JavaScript array.</p> a JavaScript array, instead of
<p id="demo"></p> a JavaScript object.
<script>
const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr[0];
</script>

</body>
</html>
Exceptions
<!DOCTYPE html> Parsing Dates
<html>
<body> • Date objects are not
<h2>Convert a string into a date object.</h2>
<p id="demo"></p> allowed in JSON.
<script> • If you need to include a
const text = '{"name":"John", "birth":"1986-12-14", "city":"New
York"}'; date, write it as a string.
const obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.getElementById("demo").innerHTML = obj.name + ", " + • You can convert it back
obj.birth;
</script> into a date object later
</body>
</html>
Exceptions
<!DOCTYPE html>
<html> Parsing Dates
<body>
• you can use the second
<h2>Convert a string into a date object.</h2>
parameter, of the
<p id="demo"></p>
JSON.parse() function, called
<script> reviver.
const text = '{"name":"John", "birth":"1986-12-14", "city":"New
York"}'; • The reviver parameter is a
const obj = JSON.parse(text, function (key, value) {
if (key == "birth") { function that checks each
return new Date(value);
} else { property, before returning the
return value;
} value.
});
document.getElementById("demo").innerHTML = obj.name + ", " +
obj.birth;
</script>

</body>
</html>
<!DOCTYPE html> Exceptions
<html>
<body> Parsing Functions

• Functions are not allowed in


<h2>Convert a string into a function.</h2>
JSON.
<p id="demo"></p>
• If you need to include a
<script> function, write it as a string.
const text = '{"name":"John", "age":"function() {return 30;}", • You can convert it back into a
"city":"New York"}';
function later
const obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")"); • You should avoid using
document.getElementById("demo").innerHTML = obj.name + ", " + functions in JSON, the
obj.age(); functions will lose their
</script>
scope, and you would have to
use eval() to convert them
</body>
</html> back into functions.
JSON.stringify
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.

• Convert a JavaScript object into a string with JSON.stringify().

Imagine we have this object in JavaScript:


const obj = {name: "John", age: 30, city: "New York"};

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
JSON.stringify( )
<!DOCTYPE html>
<html>
<body>

<h2>Create a JSON string from a JavaScript object.</h2>


<p id="demo"></p>

<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>
Stringify JavaScript Array
<!DOCTYPE html> • It is also possible to stringify JavaScript
<html>
<body> arrays

<h2>Create a JSON string from a JavaScript • Imagine we have this array in JavaScript:
array.</h2>
<p id="demo"></p> const arr = ["John", "Peter", "Sally",
"Jane"];
<script>
const arr = ["John", "Peter", "Sally", "Jane"]; • Use the JavaScript function JSON.stringify()
const myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = to convert it into a string.
myJSON;
</script> const myJSON = JSON.stringify(arr);

</body> • The result will be a string following the


</html> JSON notation.
• myJSON is now a string, and ready to be
sent to a server:
<!DOCTYPE html>
<html>
<body>
Storing Data
• When storing data, the data has to
<h2>Store and retrieve data from local storage.</h2>
<p id="demo"></p> be a certain format, and regardless
of where you choose to store it.
<script>
// Storing data: • Text is always one of the legal
const myObj = { name: "John", age: 31, city: "New
York" }; formats.
const myJSON = JSON.stringify(myObj); • JSON makes it possible to store
localStorage.setItem("testJSON", myJSON);
JavaScript objects as text.
// Retrieving data:
let text = localStorage.getItem("testJSON");
let obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
</script>

</body>
</html>
Exception
<!DOCTYPE html>
<html> Stringify Dates
<body>
• In JSON, date objects are not
<h2>JSON.stringify() converts date objects into allowed.
strings.</h2>
<p id="demo"></p> • The JSON.stringify() function will
convert any dates into strings.
<script>
const obj = {name: "John", today: new Date(), city: • You can convert the string back
"New York"};
const myJSON = JSON.stringify(obj); into a date object at the receiver.
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>
Exception
Stringify Functions
<!DOCTYPE html>
<html> • In JSON, functions are not allowed as
<body>
object values.
<h2>JSON.stringify() will remove any functions • The JSON.stringify() function will
from an object.</h2>
<p id="demo"></p> remove any functions from a

<script> JavaScript object, both the key and


const obj = {name: "John", age: function () the value
{return 30;}, city: "New York"};
const myJSON = JSON.stringify(obj); • This can be omitted if you convert
document.getElementById("demo").innerHTML =
your functions into strings before
myJSON;
</script> running the JSON.stringify() function.

</body>
</html>
Exception
<!DOCTYPE html>
<html>
<body> Stringify Functions
<h2>JSON.stringify() will remove any functions from an
• In JSON, functions are not allowed as
object.</h2> object values.
<p>Convert functions into strings to keep them in the JSON
object.</p> • The JSON.stringify() function will
<p id="demo"></p> remove any functions from a JavaScript

<script> object, both the key and the value


const obj = {name: "John", age: function () {return 30;},
city: "New York"};
• This can be omitted if you convert your
obj.age = obj.age.toString(); functions into strings before running
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON; the JSON.stringify() function.
</script>
• If you send functions using JSON, the
</body>
</html> functions will lose their scope, and the
receiver would have to use eval() to
convert them back into functions.

You might also like