Working with JSON Object

Working with JSON Object with Examples

In this article, I am going to discuss Working with JSON Objects with Examples. Please read our previous article, where we discussed jQuery Method Chaining. At the end of this article, you will understand everything about JSON Object.

What is JSON?
  1. JSON stands for JavaScript Object Notation.
  2. JSON is a format for storing and transporting data
  3. JSON is often used when data is sent from a server to a web page
  4. JSON is a lightweight data-interchange format
  5. JSON is language independent
  6. JSON is easier than XML
JSON Syntax rules:
  1. Data is in key/value pairs
  2. Data is separated by commas
  3. JSON objects are surrounded by curly braces {}
  4. Curly braces hold objects
  5. Square brackets hold arrays

The data type of JSON object’s value cannot be a date, function, or undefined. JSON supports the following data types:

  1. Objects { … }
  2. Arrays [ … ]
  3. Primitives:
  4. strings,
  5. numbers,
  6. Boolean values true/false,
  7. null.
Syntax:

Following is the syntax to create a JSON object.

JSON Syntax

Example: JSON Object

Let us understand how to work with JSON with examples. Let’s create a JSON Object first as shown below.

<script>
    var employee = {
      "firstname" : "Rick",
      "lastname" : "Brown",
      "age" : 22,
      "salary" : 15000
    }; 
</script>

Here,

  1. employee is the JSON object
  2. In the curly braces, we include the property as “key”: “value” pairs, separated by commas
  3. The Key and value of a property must be separated by using a colon (:)
  4. We can declare any number of properties inside a JSON object.

This is an example of a JSON object. Now if we want to access any of its value, then we can do it in the following way. As you can see, to read data from the JSON object, we need to use the object property names.

console.log(‘The First Name of the employee is ${employee.firstname}’);
console.log(‘The Last Name of the employee is ${employee.lastname}’);
console.log(‘The Salary of the employee is ${employee.salary}’);

Following is the complete code example.
<!DOCTYPE html>
<html>
<head>
    <title>Working with JSON</title>
</head>
<body>
  <h3>Working with JSON</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    var employee = {
      "firstname" : "Rick",
      "lastname" : "Brown",
      "age" : 22,
      "salary" : 15000
    };
    console.log(`The First Name of the employee is ${employee.firstname}`);
    console.log(`The Last Name of the employee is ${employee.lastname}`);
    console.log(`The Age of the employee is ${employee.age}`);
    console.log(`The Salary of the employee is ${employee.salary}`);
  </script>
</body>
</html>

Now run the above code and then open the browser developer tool by pressing the F12 key and then select the Console tab and you should see the following logs in the Console.

Working with JSON with Examples

How to access the JSON Object elements using jQuery Each function?

We can also use the jQuery each() utility function to access the JSON Object elements. For better understanding, please have a look at the below example, where we are accessing all the elements of the employee JSON object using the jQuery each() function.

<!DOCTYPE html>
<html>
<head>
    <title>Working with JSON</title>
</head>
<body>
  <h3>Working with JSON</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    var employee = {
      "firstname" : "Rick",
      "lastname" : "Brown",
      "age" : 22,
      "salary" : 15000
    };
    $.each( employee, function(prop, val){
          console.log(`The property is ${prop} and the value is ${val}`)
    });
  </script>
</body>
</html>

Here, we are using each() method to access all the properties of an object in a loop. With the above changes in place, now run the code and open the browser developer tool by pressing the F12 key and then have a look at the Console tab and you should see the following logs in the Console which prints the JSON object key and its corresponding value.

How to access the JSON Object elements using jQuery Each function?

JSON Array of Objects.

If you want to store more than one employee object in the JSON object, then we need to create JSON Array. The JSON array can contain more than one JSON object.

Syntax to Create JSON Array of Objects

Wrap the objects in square brackets and each object must be separated with a comma. For better understanding, please have a look at the below image which shows the syntax to create a JSON array of objects.

Syntax to Create JSON Array of Objects

Example: JSON Array of objects

Let us understand the JSON Array of objects with an example. Let’s create a JSON Array of Objects first as shown below.

var employeeList = [{
  "firstname": "Rick",
  "lastname": "Brown",
  "age": 22,
  "salary": 15000
},
{
  "firstname": "John",
  "lastname": "Doe",
  "age": 24,
  "salary": 12000
},
{
  "firstname": "Sarah",
  "lastname": "Tye",
  "age": 25,
  "salary": 17000
}];

This is a JSON array of objects. Each element of the array is a JSON object. To access the employee objects in the JSON array, we need to use the object’s index position and the index position starts from 0. That is the first employee index position is 0 and second employee object index position is 1 and so on.

Now if we have to access the 1st object then we have to use employeeList[0], and then if we have to access the first name property of the 1st object then we have to use employeeList[0].firstname. The following code snippet shows how to access each element of the first employee from the JSON array of objects.

 console.log(`The First Name of the 1st employee is ${employeeList[0].firstname}`);
console.log(`The Last Name of the 1st employee is ${employeeList[0].lastname}`);
console.log(`The Age of the 1st employee is ${employeeList[0].age}`);
console.log(`The Salary of the 1st employee is ${employeeList[0].salary}`);

Similarly, if you want to access the 2ndt object then you have to use employeeList[1], and then if you have to access the first name property of the 2nd object then you have to use employeeList[1].firstname. The following code snippet shows how to access each element of the second employee object from the JSON array of objects.

 console.log(`The First Name of the 2nd employee is ${employeeList[1].firstname}`);
console.log(`The Last Name of the 2nd employee is ${employeeList[1].lastname}`);
console.log(`The Age of the 2nd employee is ${employeeList[1].age}`);
console.log(`The Salary of the 2nd employee is ${employeeList[1].salary}`);

Now continuing in this process, we can access all the objects in the collection. Following is the complete code of the above-discussed example.

<!DOCTYPE html>
<html>
<head>
    <title>Working with JSON Array</title>
</head>
<body>
  <h3>Working with JSON Array</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    var employeeList = [{
      "firstname": "Rick",
      "lastname": "Brown",
      "age": 22,
      "salary": 15000
    },
    {
      "firstname": "John",
      "lastname": "Doe",
      "age": 24,
      "salary": 12000
    },
    {
      "firstname": "Sarah",
      "lastname": "Tye",
      "age": 25,
      "salary": 17000
    }];

    console.log(`The First Name of the 1st employee is ${employeeList[0].firstname}`)
    console.log(`The Last Name of the 1st employee is ${employeeList[0].lastname}`)
    console.log(`The Age of the 1st employee is ${employeeList[0].age}`)
    console.log(`The Salary of the 1st employee is ${employeeList[0].salary}`)

    console.log(`The First Name of the 2nd employee is ${employeeList[1].firstname}`)
    console.log(`The Last Name of the 2nd employee is ${employeeList[1].lastname}`)
    console.log(`The Age of the 2nd employee is ${employeeList[1].age}`)
    console.log(`The Salary of the 2nd employee is ${employeeList[1].salary}`)

    console.log(`The First Name of the 2nd employee is ${employeeList[2].firstname}`)
    console.log(`The Last Name of the 2nd employee is ${employeeList[2].lastname}`)
    console.log(`The Age of the 2nd employee is ${employeeList[2].age}`)
    console.log(`The Salary of the 2nd employee is ${employeeList[2].salary}`)

  </script>
</body>
</html>

Now run the above code and open the browser developer tool by pressing the F12 key and then have a look at the Console tab and you should see the following logs in the Console.

JSON Array of objects Example

But this is too lengthy. We can use the jQuery each() method to access our objects in a loop as shown in the below example.

<!DOCTYPE html>
<html>
<head>
    <title>Working with JSON Array</title>
</head>
<body>
  <h3>Working with JSON Array</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(document).ready(function () {
    var employeeList = [{
      "firstname": "Rick",
      "lastname": "Brown",
      "age": 22,
      "salary": 15000
    },
    {
      "firstname": "John",
      "lastname": "Doe",
      "age": 24,
      "salary": 12000
    },
    {
      "firstname": "Sarah",
      "lastname": "Tye",
      "age": 25,
      "salary": 17000
    }];

    $.each(employeeList, (index, item) => {
      console.log(`Index no ${index} :- The Full Name of the employee is ${item.firstname} ${item.lastname}.
       His age is ${item.age} and salary is ${item.salary}`)
    });
   });
  </script>
</body>
</html>

With the above changes in place, now run the code and open the browser developer tool by pressing the F12 key and then have a look at the Console tab and you should see the following logs in the Console.

Accessing JSON Array of objects using jQuery Each method

JSON Nested Object:

It is also possible to store multiple JSON objects in the JSON object by nesting them. Following is the syntax to store multiple JSON objects by nesting them.

JSON Nested Object Syntax

Example: Nested JSON Objects

Let us understand how to store multiple JSON objects by nesting them with an example. Please have a look at the below code.

var employeeDetails = {
    "Basic": {
      "firstname": "Rick",
      "lastname": "Brown",
      "age": 22,
      "salary": 15000
    },
    "Address": {
      "Country": "India",
      "State": "Odisha",
      "City": "Bhubaneswar"
    }
};

This is an example of a nested object. Here employeeDetails is an object. Basic and Address are its property. Again, Basic and Address are objects.

The Basic property can be accessed by employeeDetails.Basic. This is again an object, so the firstname property can be accessed as employeeDetails.Basic.firstname and in the same way you can access the other properties.

The Address property can be accessed by employeeDetails.Address. As Address is again an object, so the Country property can be accessed as employeeDetails.Address.Country and in the same way you can access the other properties of the Address object.

Following is the complete code of the above-discussed example.
<!DOCTYPE html>
<html>
<head>
    <title>Working with Nested JSON Object</title>
</head>
<body>
  <h3>Working with Nexted JSON Object</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
  var employeeDetails = {
      "Basic": {
        "firstname": "Rick",
        "lastname": "Brown",
        "age": 22,
        "salary": 15000
      },
      "Address": {
        "Country": "India",
        "State": "Odisha",
        "City": "Bhubaneswar"
      }
  };

  console.log(`The First Name of the employee is ${employeeDetails.Basic.firstname}`);
  console.log(`The Last Name of the employee is ${employeeDetails.Basic.lastname}`);
  console.log(`The Age of the employee is ${employeeDetails.Basic.age}`);
  console.log(`The Salary of the employee is ${employeeDetails.Basic.salary}`);

  console.log(`The Country of the employee is ${employeeDetails.Address.Country}`);
  console.log(`The State of the employee is ${employeeDetails.Address.State}`);
  console.log(`The City of the employee is ${employeeDetails.Address.City}`);
  </script>
</body>
</html>

Run the above code and open the browser developer tool by pressing the F12 key and then have a look at the Console tab and you should see the following logs in the Console.

Working with Nested JSON Object

Ye can also use the jQuery each() method to iterate through the properties of the nested objects which is shown in the below example.

<!DOCTYPE html>
<html>
<head>
    <title>Working with Nexted JSON Object</title>
</head>
<body>
  <h3>Working with Nexted JSON Object</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
  var employeeDetails = {
      "Basic": {
        "firstname": "Rick",
        "lastname": "Brown",
        "age": 22,
        "salary": 15000
      },
      "Address": {
        "Country": "India",
        "State": "Odisha",
        "City": "Bhubaneswar"
      }
  };
  $.each(employeeDetails, function(prop, val){
    $.each(employeeDetails[prop], function( props, vals ){
      console.log(` ${props} : ${vals} `);
    });
  });

  </script>
</body>
</html>
Output:

Working with Nested JSON Object using each method

In the next article, I am going to discuss How to Convert JSON Objects to String and String to JSON Objects with Examples. Here, in this article, I try to explain Working with JSON Object with Examples and I hope you enjoy this Working with JSON Object article.

1 thought on “Working with JSON Object”

Leave a Reply

Your email address will not be published. Required fields are marked *