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

JSON_Session

The document provides an extensive overview of JSON (JavaScript Object Notation), including its structure, how to manipulate JSON objects and arrays, and methods for fetching JSON data using AJAX and jQuery. It also covers accessing object values, looping through properties, and modifying array values, along with examples of nested arrays and deleting items. Additionally, it discusses APIs, structured data formats, and provides links to JSON formatter tools and popular JSON APIs.

Uploaded by

gayathri Jayalal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JSON_Session

The document provides an extensive overview of JSON (JavaScript Object Notation), including its structure, how to manipulate JSON objects and arrays, and methods for fetching JSON data using AJAX and jQuery. It also covers accessing object values, looping through properties, and modifying array values, along with examples of nested arrays and deleting items. Additionally, it discusses APIs, structured data formats, and provides links to JSON formatter tools and popular JSON APIs.

Uploaded by

gayathri Jayalal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

JSON- JAVASCRIPT OBJECT NOTATION

Sites to verify json:


https://www.jsoneditoronline.org
 Sort data in Ascending order. (Ex : age ,Hobbies ,name, Sex)
var student = {
"name": "Aswathy",
"age": 26,
"Sex": "Female",
"Hobbies": [
"Reading",
"Acting",
"Gardening"
]
}
 student .Qualification = “Btech”
 student

var student = {
“age”: 26,
“Hobbies”: [
“Reading”,
“Acting”,
“Gardening”
],
“name”: “Aswathy”,
“Qualification”:”Btech”,
“Sex”: “Female”
}
 student.age=20
 student

var student = {
“age”: 20,
“Hobbies”: [
“Reading”,
“Acting”,
“Gardening”
]
“name”: “Aswathy”,
“Qualification”:”Btech”,
“Sex”: “Female”
}
 delete (student.Sex)
 return true
 student
var student = {
“age”: 20,
“Hobbies”: [
“Reading”,
“Acting”,
“Gardening”
],
“name”: “Aswathy”,
“Qualification”:”Btech”
}
 In console window js is actually processed.
 delete(student.Hobbies[0])
 return true
 student
 index 0th value will get deleted, but length : 3. So while working with array delete
doesn’t work well. So we can use splice in such cases.
var student = {
“age”: 20,
“Hobbies”: [
“Acting”,
“Gardening”
]
“name”: “Aswathy”,
“Qualification”:”Btech”
}
 Splice
 student.Hobbies.splice(0,1)
 Return undefined 0 , because 0th index is already deleted.
 Student.Hobbies.splice(1,1)
 It will remove 1st index i.e; value Gardening from the Hobbies Array.
 In hobbies, 0: Acting & length : 1
 student
var student = {
“age”: 20,
“Hobbies”: [
“Acting”
]
“name”: “Aswathy”,
“Qualification”:”Btech”
}
 If we apply a debug point, it will stop there.
 We can check if any variable has executing property or not.

var student = {
“age”: 20,
“Hobbies”: [
“Acting”
],
“name”: “Aswathy”,
“Qualification”:”Btech”,
“subject”:[
{AI: “Artificial Intelligence”},
{ML:”Machine Learning”}
]
}
 student.subject
 we get an array(2),
 0: Object
 AI : Artificial Intelligence
 1:Object
 ML: Machine Learning
 Length: 2
for(var i=0;i<=student.subject.length;i++){
for(key in student.subject[i]){
console.log(key);
}
}
 Output : AI, ML
Let’s say we have JSON data in employees.json file. Inorder to fetch this json data & show it in
div’s in index.html file, we can do it using Ajax or Jquery.
 Fetching JSON data using AJAX(Asynchronous Javascript And XML)

Script.js

var xhr = new XMLHttpRequest();


xhr.open(‘GET’,employees.json);

xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){

var employees1 = JSON.parse(xhr.responseText);


var html1 = ‘<ul>’;

for(var i=0; i< employees1.length; i++){


html1 = ‘<li>’ + employees1[i].name + ‘<li>’;
}
html1+= ‘<ul>’;
document.getElementById(‘employees1’).innerHTML=html1;

}
}
};
xhr.send();

Index.html

<div> id=”employees1”</div>

 Fetching JSON data using jQuery(Simplifies AJAX call & DOM manipulation)
 JQUERY is a Javascript Library.

$(document).ready(function(){

$.getJSON(‘employees.json’,function(data){

var html2=’<ul>’;
$.each(data, function(index,employee){
html2=’<ul>’ + employee.name + ‘<ul>’;
});
html2+=’</ul>’;
document.getElementById(‘employees2’).innerHTML=html2;
});
});
Index.html

<div id=”employees2></div>
 Add all js library and js script tags below your content.
 Also make sure all frameworks or external libraries like jquery is added 1 st, then only
add script tag for js files. Otherwise data won’t be visible in view.

Popular JSON API’s


 https://maps.openweathermap.org
 https://maps.googleapis.com
module.exports= function(){

const data = require("./testdata.json");

/*Explore the JSON file and return required JSON data*/


// $.getJSON("testdata.json", function(data){
// console.log(data);
// });

var xhr = new XMLHttpRequest();


xhr.open('GET',"testdata.json");

xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
var data = JSON.parse(xhr.responseText);
console.log(data);
}
}
}
}

Accessing Object Values


 dot ('.') and bracket [ ] notation is used to access Object Values.

Example 1
<p>Access a JSON object using bracket notation:</p>
<p id="Sample"></p>

<script>
var myObj, x;
myObj = { "name":"Arun", "age":28, "Company":"TCS"};
x = myObj["Company"];
document.getElementById("Sample").innerHTML = x;
</script>

OR

Example 2

<p>Access a JSON object using bracket notation:</p>


<p id="Sample"></p>
<script>
var myObj, x;
myObj = { "name":"Arun", "age":28, "Company":"TCS"};
x = myObj.Company;
document.getElementById("Sample").innerHTML = x;

Looping an Object
 for-in loop can be used to loop in object properties.

Example

<p>How to loop through all properties in a JSON object.</p>


<p id="sample"></p>
<script>
var myObj, x;
myObj = { "name":"Arun", "age":28, "Company":"TCS"};
for (x in myObj) {
document.getElementById("sample").innerHTML += x + "<br>";
}
</script>

Example:

Utilize the bracket notation for accessing the property values.

for (x in myObj) {
document.getElementById("sample").innerHTML += myObj[x] + "<br>";
}

File Name: tindex.js

module.exports= function(){

const data = require("./testdata.json");

/*Explore the JSON file and return required JSON data*/

var json = JSON.parse(data).studentData;

json.forEach(function(element, index){

element['aggregate'] = parseInt(element['aggregate']);

element.forEach(function(per,ind){

per['sub1'] = parseInt(per['sub1']);

per['sub2'] = parseInt(per['sub2']);

per['sub3'] = parseInt(per['sub3']);

}); });

return json;
}

Accessing an Array
Example
<p>Access an array value of a JSON object</p>
<p id="Sample"></p>
<script>
var myObj, x;
myObj = {
"name":"Arun",
"age":29,
"cars":["Hyundai", "Volkswagen", "Maruti Suzuki"]
};
x = myObj.cars[0];
document.getElementById("Sample").innerHTML = x;
</script>

Looping an Array - Example

<p>Looping through an array using a for in loop:</p>


<p id="Sample"></p>
<script>
var myObj, i, x = "";
myObj = {
"name":"Arun",
"age":29,
"cars":["Hyundai", "Volkswagen", "Maruti Suzuki"]
};
for (i in myObj.cars) {
x += myObj.cars[i] + "<br>";
}
document.getElementById("Sample").innerHTML = x;
</script>

To Modify Array Values

 Use the index number to modify an array values.

`myObj.cars[1] = "Maruti suzuki";


Example

<p>Looping through an array using a for in loop:</p>


<p id="Sample"></p>
<script>
var myObj, i, x = "";
myObj = {
"name":"Arun",
"age":29,
"cars":["Hyundai", "Volkswagen", "Maruti Suzuki"]
};
myObj.cars[1] = "Mercedes";
for (i in myObj.cars) {
x += myObj.cars[i] + "<br>";
}
document.getElementById("Sample").innerHTML = x;
</script>

Nested Array
In Nested arrays, to access arrays inside arrays, use a for-in loop for each
array.

Example

<p>Looping through arrays inside arrays.</p>


<p id="Sample"></p>
<script>
var myObj, i, j, x = "";

myObj = {
"name":"Arun",
"age":28,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
for (i in myObj.cars) {
x += "<h2>" + myObj.cars[i].name + "</h2>";
for (j in myObj.cars[i].models) {
x += myObj.cars[i].models[j] + "<br>";
}
}
document.getElementById("Sample").innerHTML = x;
</script>

To Delete Array Items

 Use the delete keyword to delete items from an array

<p>How to delete properties of an array.</p>


<p id="Sample"></p>
<script>
var myObj, i, x = "";
myObj = {
"name":"Arun",
"age":29,
"cars": ["Ford","BMW","Fiat"]
}

delete myObj.cars[1];
for (i in myObj.cars) {
x += myObj.cars[i] + "<br>";
}
document.getElementById("Sample").innerHTML = x;
</script>

"persons":{

"Name":"Gayathri",

"EmployeeID": 12321,

"Experience" : 2,

"Company": "TCS",

"Designation": "Software Engineer"

JSON Parse - Example


You have to use JavaScript function JSON.parse() to convert this text into a
JavaScript object:

<h2>Create Object from JSON String</h2>


<p id="sample"></p>
<script>
var obj = JSON.parse('{ "name":"Arun", "age":28, "city":"Chennai"}');
document.getElementById("sample").innerHTML = obj.name + ", " + obj.age+ ", "
+ obj.city;
</script>

[
{
"Name":"Pizza",
"Type":"Food",
"Price":300
},
{
"Name":"Burger",
"Type":"Food1",
"Price":200
},
{
"Name":"Sandwich",
"Type":"Food2",
"Price":250
}
]

 Use the JavaScript function JSON.stringify() to convert it into a string.

var myJSON = JSON.stringify(obj);`

Example

To Stringify a JavaScript Array

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


<p id="sample"></p>
<script>
var obj = { "Country":"India", "Location":"Agra", "Distance":200,
"Monument":"Taj Mahal"}
var myJSON = JSON.stringify(obj);
document.getElementById("sample").innerHTML = myJSON;
</script>

API -APPLICATION PROGRAMMING INTERFACE


 It defines how two pieces of software talk to each other.
WEB API

First Web API was created by – ebay


 Programmableweb.com website keep track of all the web API’s that
are publicly available to use.
 Two types of structured data formats – JSON(Javascript Object
Notation) & XML(Extensible Markup Language).
 Structured data doesn’t fit into a table.
JSON has 3 types – Number, String, Boolean
XML has 1 type – String
Collections – Groups of data
Two types-
 Arrays(lists of data values)
1. A Size – how many are in the list
2. An Order – which object comes first, then which comes second &
third.
 Dictionaries(look up tables)
1. A dictionary is a collection of data keys & values.
2. The idea is you use the key to look up the values.
 Structured data combines data type & collections
 You can have:
1. List of Dictionaries
2. Dictionaries of list
3. Dictionaries of Dictionaries
4. Etc as many levels as u need.
 Structured data has a Tree structure where each collection is branch and
at the end of each branch is a data value.
 API’s have request & responses.
 Responses almost always have structured data.
 Responses return information from the server in the form of structured
data.
 Sometimes request uses structured data to pass information to the
server.
 JSON – Most popular way of sending data to web API’s.
 Strings, Number, Booleans, Null, Arrays, Objects
 Objects are JSON’s dictionaries.
 Nesting involves putting arrays & objects inside each other.
JSON FORMATTER TOOL:
https://www.freeformatter.com/json-formatter.html#ad-output
https://www.freeformatter.com/xml-formatter.html
Documentation:
http://dita.xml.org/
Swagger
<dailyForecast>
<date>2015-06-01</date>
<description>sunny</description>
<maxTemp unit="C">22</maxTemp>
<minTemp unit="C">20</minTemp>
<windSpeed unit="kph">12</windSpeed>
<danger>false</danger>
</dailyForecast>

{
"Monday": {
"description": "sunny",
"maxTemp": 22,
"minTemp": 20,
"windSpeed": 12,
"danger": false
}
}

{
"forecast": [
{
"Monday": {
"description": "sunny",
"maxTemp": 22,
"minTemp": 20,
"windSpeed": 12,
"danger": false
}
},
{
"Tuesday": {
"description": "windy",
"maxTemp": 22,
"minTemp": 20,
"windSpeed": 40,
"danger": true
}
},
{
"Wednesday": null
}
]
}

Represents a Weather Forecast


Element Description Type Required Notes
Date Date of the weather string Required Format is YYYY-MM-DD
forecast
description Description about the string Optional It can have values
weather sunny, overcast, partly
cloudy, raining, snowing
maxTemp HIGH temperature number Required Value is in degree celsius
minTemp LOW Temperature number Required Value is in degree celsius

windSpeed Speed of wind number Required Value is in kilometers


per hour
Danger True if weather boolean
conditions are
dangerous, otherwise
false

You might also like