JavaScript Day6
JavaScript Day6
Day 6
What is JSON?
<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
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()
<p id="demo"></p>
</body>
</html>
<script>
Example
</body>
<p id="demo"></p>
</html>
<script>
Example
<p id="demo"></p>
</body>
</html>
<script>
JSON Objects
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