How to select values from a JSON object using jQuery?


JSON or JavaScript Object Notation is a lightweight format used for data interchange between web applications and servers. It provides a simple and easy-to-read structure that can be parsed and generated easily by machines. JSON is often used as an alternative to XML because it is more compact and easier to work with.

In this article, we see how to select values from a JSON object using jQuery with different approaches.

What is a JSON object?

A JSON object consists of a collection of key-value pairs separated by colons. Here keys are known as strings and the values are of some valid JSON data types which include strings, numbers, boolean, null, objects, or arrays.

Let’s now see the syntax of JSON objects.

How the JSON data look like

The code or syntax given below is an example of a JSON object.

{
   "id": 1,
   "name": "Leanne Graham",
   "username": "Bret",
   "email": "Sincere@april.biz",
   "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
         "lat": "-37.3159",
         "lng": "81.1496"
      }
   },
   "phone": "1-770-736-8031 x56442",
   "website": "hildegard.org",
   "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
   }
}

The above syntax of JSON data object consists of various properties like a "name", "email", and some nested "address", and "company" objects, etc. Now sometimes we need to select values from this object but how? With the help of jQuery, we can easily fetch or select the value from the JSON objects.

Approaches to select values from a JSON object using jQuery

Approach 1: Using each() or append() method

The first approach to select the values from JSON data with the help of jQuery is by using the $.each() function. Each function is also known as the append() method because here also the append() method is used to dynamically add the HTML elements. In this function, we loop through the JSON data objects after which we access their properties.

Note that, this method is effective only when the JSOB data objects consist of a few nested levels. It can be also used to access values at any level of nesting. Below is the syntax for using each() method −

Syntax

$.each(dataObj, function(key, value) {
   $("#html-element-id").append("<p>" + key + ": " + value + "</p>");
});

In the above syntax, the $.each() method first loops through each key-value pair in the dataObj JSON object after which it displays the output in an HTML element with the id=”html-element-id”. To be more concise in selecting the limited type of data, we can also use an if statement inside the method to select some of the specific properties.

Example

<!DOCTYPE html>
<html>
<head>
   <title>JSON Object Selection</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
   <h1>JSON data output</h1>
   <div id="data-output"></div>
   <script>
      // JSON data object
      var dataObj = {
         "name": "Tutorialspoint",
         "type": "Education",
         "address": {
            "state": "Delhi",
            "country": "India"
         }
      };
      $.each(dataObj, function (key, value) {
         $("#data-output").append("<p>" + key + ": " + JSON.stringify(value) + "</p>");
      });
   </script>
</body>
</html>

Output

In this example, we have used each() method with append() to select the JSON objects. Here, the $.each() function iterates through each key-value pair in the dataObj JSON object and logs each key-value pair to the div element with the help of the #data-output ID.

Approach 2: Using dot notation

The second approach to select the values from JSON data with the help of jQuery is by using dot notation. Here the JSON data values are accessible using the dot notation which allows the users to directly access the data objects' properties.

It can be also used to access values at any level of nesting. Below is the syntax for using the dot notation method −

Syntax

$("#html-elment-id").append("<p>" + dataObj.name + "</p>");
$("#html-elment-id").append("<p>" + dataObj.address.state + "</p>");
$("#html-elment-id").append("<p>" + dataObj.type + "</p>");

In the above syntax, the dot notation is used to directly access the properties of the “dataObj” JSON object. We are also displaying the output in an HTML element with the id=”html-element-id”.

Example

<!DOCTYPE html>
<html>
<head>
   <title>JSON Object Selection</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
   <h1>JSON data output</h1>
   <div id="html-element-id"></div>
   <script>
      // JSON data object
      var dataObj = {
         "name": "Tutorialspoint",
         "type": "Education",
         "address": {
            "state": "Delhi",
            "country": "India"
         }
      };
      $("#html-element-id").append("<p>" + dataObj.name + "</p>");
      $("#html-element-id").append("<p>" + dataObj.type + "</p>");
      $("#html-element-id").append("<p>" + dataObj.address.state + "</p>");
   </script>
</body>
</html>

Output

In this example, we have used dot notation to select the JSON objects. We have accessed the values of the name, type, and state from the address within the dataObj JSON object. All the three keys are strings within the array of objects. After accessing all of these three objects, these are displayed in the <p> element with the help of the #html-element-id ID.

Approach 3: Using Bracket Notation

The third and last approach to select the values from JSON data with the help of jQuery is by using bracket notation []. Here the JSON data values are accessible using the bracket notation i.e we use the [] notation that allows the users to directly access the data object's nested properties.

This approach is useful when the property names of the JSON objects consist of some special characters or may have any spaces. Below is the syntax for using the bracket notation method −

Syntax

$("#data-output").append("<p>" + dataObj["name"] + "</p>");
$("#data-output").append("<p>" + dataObj["type"] + "</p>");
$("#data-output").append("<p>" + dataObj["address"]["state"] + "</p>");

In the above syntax, the bracket notation is used to access the properties of the “dataObj” JSON object. It is commonly used when we want to access properties with special characters or spaces in their names. We are also displaying the output in an HTML element with the id=”html-element-id”.

Example

<!DOCTYPE html>
<html>
<head>
   <title>JSON Object Selection</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
   <h1>JSON data output</h1>
   <div id="data-output"></div>
   <script>
      // JSON data object
      var dataObj = {
         "name": "Tutorialspoint",
         "type": "Education",
         "address": {
            "state": "Delhi",
            "country": "India"
         }
      };
      $("#data-output").append("<p>" + dataObj["name"] + "</p>");
      $("#data-output").append("<p>" + dataObj["type"] + "</p>");
      $("#data-output").append("<p>" + dataObj["address"]["state"] + "</p>");
   </script>
</body>
</html>

Output

In this example, we have used bracket notation to select the JSON objects. We have accessed the values of the name, type, and state from the address within the dataObj JSON object. All the three keys are strings within the array of objects. After accessing all of these three objects, these are displayed in the <p> element using the append() method with help of the #html-element-id ID.

Conclusion

In this article, we saw how to select the data values from the JSON objects. To select the values, there are three approaches discussed to extract data from a JSON object: The each() method/append() method, dot notation, and bracket notation.

To know which method is good or bad, each of them has its own advantages or disadvantages which also depends on the level of nested data and the specific data required. If the developers take these approaches to make their application, they can easily manipulate JSON data effectively and display it dynamically in HTML elements.

Updated on: 10-May-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements