Krivalar Tutorials 
Krivalar Tutorials

JSON-Object


What is JSON? JSON Syntax JSON Data Types JSON vs XML JSON Array JSON Object


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:
  1. By using dot(.) notation
  2. 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

<< Previous - JSON Array

Next - Introduction to JSON >>