An Insight Into JSON And How Its working

Posted By : Vinay Tiwari | 29-Apr-2018
This blog explains us, What is JSON. JSON stands for JavaScript Object Notation. JSON is a lightweight data interchange format. JSON is an easier to use alternative to XML.
 
Creating and accessing data from a JSON object
	//creating a JSON object
	$(document).ready(function(){
		var employeeJSON = {
			"firstName": "Tode",
			"lastName": "Baker",
			"gender": "Male",
			"salary": 50000
		};
		var result = '';
		result+= 'First Name = ' +employeeJSON.firstName + '
';
		result+= 'Last Name = ' +employeeJSON.lastName + '
';
		result+= 'Gender = ' +employeeJSON.gender + '
';
		result+= 'Salary = ' +employeeJSON.salary + '
';
		
		$('#divResult').html(result);
		
	});
 
HTML code:-

 
 
 
Here is the result:-
First Name = Tode
Last Name = Baker
Gender = Male
Salary = 50000
 
Here is explaination of JSON object
1). employeeJSON is a JSON object
2). include the "name":"value" pairs, separated by commas in the curly braces
3). separate the name and value of a property by using a colon(:)
4). declare any number of properties
 
Property names are used to read the JSON object
var firstName = employeeJSON.firstName;
 
JSON Arrays: JSON arrays are used when you would like to store more than 1 employee data in the JSON object.
 
To create a JSON array
1). Wrap the objects in square brackets 
2). Each object must be separated by the comma 
 
Let's look at an example:-
var employeeJSON = [
	{
		"firstName": "Tode",
		"lastName": "Baker",
		"gender": "Male",
		"salary": 50000
	},
	{
		"firstName": "Saransh",
		"lastName": "Grover",
		"gender": "Female",
		"salary": 40000
	}
];
 
Reading from a JSON array:
var result = employeeJSON[0].lastName // result is Grover
 
Nested JSON object: With the help of nested JSON object we have store multiple employees data in the JSON object by nesting them 
 
let's look at an example:- 
var employeeJSON = {
	"Todd": {
		"firstName": "Tode",
		"lastName": "Baker",
		"gender": "Male",
		"salary": 50000
	},
	"Sara": {
		"firstName": "Saransh",
		"lastName": "Grover",
		"gender": "Female",
		"salary": 40000
	}
};
 
Retrieves the gender of employee Tode
var result = employeeJSON.Tode.gender;
 

Thanks

 

About Author

Author Image
Vinay Tiwari

Vinay is a bright UI developer, having knowledge of HTML, CSS, Bootstrap, Jquery and AngularJs. His hobbies are interacting with people, listening music etc.

Request for Proposal

Name is required

Comment is required

Sending message..