0% found this document useful (0 votes)
5 views

JavaScript Day6

JSON (JavaScript Object Notation) is a lightweight, language-independent data interchange format that is easy to understand and self-describing. It consists of data in name/value pairs, supports various data types, and can be easily converted between JavaScript objects and JSON strings using methods like JSON.stringify() and JSON.parse(). JSON is often preferred over XML for data exchange due to its simplicity and efficiency.

Uploaded by

pranav
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
0% found this document useful (0 votes)
5 views

JavaScript Day6

JSON (JavaScript Object Notation) is a lightweight, language-independent data interchange format that is easy to understand and self-describing. It consists of data in name/value pairs, supports various data types, and can be easily converted between JavaScript objects and JSON strings using methods like JSON.stringify() and JSON.parse(). JSON is often preferred over XML for data exchange due to its simplicity and efficiency.

Uploaded by

pranav
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/ 24

Javascript

Day 6
What is JSON?

• JSON stands for JavaScript Object Notation


• JSON is a lightweight data interchange format
• JSON is language independent *
• JSON is "self-describing" and easy to understand
 JSON Syntax Rules
• Data is in name/value pairs
• Data is separated by commas
• Curly braces hold objects
• Square brackets hold arrays
JSON Values
In JSON, values must be one of the following data types:
a string
a number
an object (JSON 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" }
Java Script
{ name:'John' }
Example

<!DOCTYPE html> 31, city: "New York" };


<html> var myJSON =
JSON.stringify(myObj);
<body>
window.location = "demo_json.php?
x=" + myJSON;
<h2>Convert a JavaScript object
</script>
into a JSON string, and send it to the
server.</h2>
</body>
<script> </html>
var myObj = { name: "John", age:
Example

<!DOCTYPE html> var myJSON = '{"name":"John",


"age":31, "city":"New York"}';
<html>
var myObj = JSON.parse(myJSON);
<body>
document.getElementById("demo").i
nnerHTML = myObj.name;
<h2>Convert a string written in JSON
</script>
format, into a JavaScript
object.</h2>
</body>
<p id="demo"></p> </html>

<script>
Example
<!DOCTYPE html> localStorage.setItem("testJSON", myJSON);
<html> // Retrieving data:
<body> text = localStorage.getItem("testJSON");
<h2>Store and retrieve data from local obj = JSON.parse(text);
storage.</h2>
document.getElementById("demo").innerHTML =
<p id="demo"></p> obj.name;
<script> </script>
var myObj, myJSON, text, obj; </body>
// Storing data: </html>
myObj = { name: "John", age: 31, city: "New York"
};
myJSON = JSON.stringify(myObj);
JSON vs XML
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 vs xml

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
Why JSON is Better Than XML

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
JSON Data Types

• a string
• a number
• an object (JSON object)
• an array
• a boolean
• null
JSON.parse()

<!DOCTYPE html> var txt = '{"name":"John", "age":30,


"city":"New York"}'
<html>
var obj = JSON.parse(txt);
<body>
document.getElementById("demo").
innerHTML = obj.name + ", " +
<h2>Create Object from JSON obj.age;
String</h2>
</script>

<p id="demo"></p>
</body>
</html>
<script>
Example

<!DOCTYPE html> JSON.parse(this.responseText);


<html>
document.getElementById("demo").innerHT
<body>
ML = myObj.name;
<h2>Use the XMLHttpRequest to get the
}
content of a file.</h2>
};
<p>The content is written in JSON format,
and can easily be converted into a JavaScript xmlhttp.open("GET", "json_demo.txt", true);
object.</p>
xmlhttp.send();
<p id="demo"></p>
</script>
<script>
<p>Take a look at <a href="json_demo.txt"
var xmlhttp = new XMLHttpRequest(); target="_blank">json_demo.txt</a></p>
xmlhttp.onreadystatechange = function() { </body>
if (this.readyState == 4 && this.status == </html>
200) {
var myObj =
Example
<!DOCTYPE html>
document.getElementById("demo").innerHT
<html>
ML = myArr[0];
<body>
}
};
<h2>Content as Array.</h2>
xmlhttp.open("GET", "json_demo_array.txt",
<p>Content written as an JSON array will be true);
converted into a JavaScript array.</p>
xmlhttp.send();
</script>
<p id="demo"></p>

<p>Take a look at <a


<script> href="json_demo_array.txt"
var xmlhttp = new XMLHttpRequest(); target="_blank">json_demo_array.txt</a><
/p>
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status ==
200) { </body>

var myArr = </html>


JSON.parse(this.responseText);
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().

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


//Use the JavaScript function JSON.stringify() to convert it into a string.
var myJSON = JSON.stringify(obj);
Example

<!DOCTYPE html> var obj = { name: "John", age: 30,


city: "New York" };
<html>
var myJSON = JSON.stringify(obj);
<body>
document.getElementById("demo").
innerHTML = myJSON;
<h2>Create JSON string from a
</script>
JavaScript object.</h2>

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

<script>
Example

<!DOCTYPE html> var arr = [ "John", "Peter", "Sally",


"Jane" ];
<html>
var myJSON = JSON.stringify(arr);
<body>
document.getElementById("demo").in
nerHTML = myJSON;
<h2>Create JSON string from a
JavaScript array.</h2>
</script>

<p id="demo"></p>
</body>
</html>
<script>
JSON Objects

 JSON objects are surrounded by curly braces {}.


 JSON objects are written in key/value pairs.
 Keys must be strings, and values must be a valid JSON data type
(string, number, object, array, boolean or null).
 Keys and values are separated by a colon.
 Each key/value pair is separated by a comma.
Example

<!DOCTYPE html> myObj = {"name":"John", "age":30,


"car":null};
<html>
for (x in myObj) {
<body>

document.getElementById("demo").in
<p>How to loop through all properties nerHTML += x + "<br>";
in a JSON object.</p>
}
</script>
<p id="demo"></p>

</body>
<script>
</html>
var myObj, x;
Nested JSON Example
<!DOCTYPE html> "car3":"Fiat"
<html> }
<body> }
<p>How to access nested JSON document.getElementById("demo").i
objects.</p> nnerHTML += myObj.cars.car2 +
"<br>";
<p id="demo"></p>
//or:
<script>
document.getElementById("demo").i
var myObj = {
nnerHTML += myObj.cars["car2"];
"name":"John",
</script>
"age":30,
</body>
"cars": {
</html>
"car1":"Ford",
"car2":"BMW",
JSON Arrays
<!DOCTYPE html> "age":30,
<html> "cars":[ "Ford", "BMW", "Fiat" ]
<body> };
x = myObj.cars[0];
<p>Access an array value of a JSON document.getElementById("demo").
object.</p> innerHTML = x;
</script>
<p id="demo"></p>
</body>
<script> </html>
var myObj, x;
myObj = {
"name":"John",
Example
<!DOCTYPE html> {"name":"Fiat", "models":["500",
"Panda"] }
<html><body>
]
<p>Looping through arrays inside
arrays.</p> }
<p id="demo"></p> for (i in myObj.cars) {
<script> x += "<h2>" + myObj.cars[i].name
+ "</h2>";
var myObj, i, j, x = "";
for (j in myObj.cars[i].models) {
myObj = {
x += myObj.cars[i].models[j] +
"name":"John",
"<br>";
"age":30,
}
"cars": [
}
{"name":"Ford", "models":["Fiesta",
document.getElementById("demo").in
"Focus", "Mustang"]},
nerHTML = x;
{"name":"BMW", "models":["320",
</script></body></html>
"X3", "X5"]},
Example

<!DOCTYPE html> "cars":[ "Ford", "BMW", "Fiat" ]


<html> };
<body> myObj.cars[1] = "Mercedes";

<p>How to modify an array value of a JSON for (i in myObj.cars) {


object.</p>
x += myObj.cars[i] + "<br>";
}
<p id="demo"></p>
document.getElementById("demo").innerHTML =
x;
<script> </script>
var myObj, i, x = "";
myObj = { </body>
"name":"John", </html>
"age":30,
Example

<!DOCTYPE html> "cars": ["Ford","BMW","Fiat"]


<html> }
<body> delete myObj.cars[1];

<p>How to delete properties of an for (i in myObj.cars) {


array.</p>
x += myObj.cars[i] + "<br>";
}
<p id="demo"></p>
document.getElementById("demo").innerH
TML = x;
<script> </script>
var myObj, i, x = "";
myObj = { </body>
"name":"John", </html>
"age":30,

You might also like