JSON-Object
What is JSON? JSON Syntax JSON Data Types JSON vs XML JSON Array JSON Object
- In JSON, an Object is a collection of an unordered list of key/value pairs.
- The Key and value is sperated by colon.
- The keys are represented as a string that is enclosed by double quotes.
- The values are represented as any valid data types such as number, string, array, boolean or null, etc.
- Each key /value pair is separated by a comma.
- The object is enclosed by curly braces({ }).
- If an array has N number of objects, each object is separated by a comma.
Syntax - Creating an Object
myObject = {
"Name" : "Ram",
"ID_NO" : "ID_2781",
"Age" : "36"
}
Accessing an Object values
We can access object values in two ways:- By using dot(.) notation
- By using square bracket([]) notation
Example for accessing object values by using dot(.) notation
<!DOCTYPE html>
<html>
<body>
<h2>Welcome</h2>
<p id="obj"></p>
<script>
//creating the object("myObj")
var myObj = {
"Name": "Ram",
"ID_NO": "ID_2028",
"Dept": "CSE"
};
// Accessing object values
var staff_name = myObj.Name;
//Prints the staff details
document.getElementById("obj").innerHTML = staff_name;
</script>
</body>
</html>
Output
Example for accessing object values by using square bracket([ ]) notation
<!DOCTYPE html> <html> <head> <script> //creating the object("empObj") var empObj = { "FirstName": "Ram", "LastName" :"Kumar", "EmpID": "ID_2028", "Dept": "Admin" }; // Accessing object values var emp_name = empObj["LastName"]; //Prints the staff details document.write("<h2>Welcome to the Department"<h2>"); document.write("<p>Emp_FirstName="+empObj["FirstName"]+"</p>"); document.write("</br>"); document.write("<p>Emp_LastName="+emp_name+"</p>"); </script> </body> </html>
Output
Example for accessing all properties of an object
<!DOCTYPE html> <html> <head> <script> //creating the object("empObj") var empObj = { "FirstName": "Ram", "LastName" :"Kumar", "EmpID": "ID_2028", "Dept": "Admin" }; document.write("<h2>Welcome to the Department"<h2>"); // Accessing object values using for..in loop for(var i in empObj) { document.write(i+ " : " + empObj[i]); document.write("</br>"); document.write("</br>"); } </script> </body> </html>
Output
Next - Introduction to JSON >>