How to search JSON tree with the help of jQuery?


JSON (JavaScript Object Notation) is a data format that is widely used when transmitting data between the server and a web application. In many cases, the JSON data has a complex structure, and searching for specific data requires some special function implementation. jQuery, a popular JavaScript library, provides powerful methods to navigate and search JSON trees efficiently using the .each() method, filter(), and grep methods. In this article, we will explore all these methods to search JSON trees with the help of jQuery.

Understanding JSON Trees

JSON data is organized in a hierarchical structure, often referred to as a JSON tree. It consists of key−value pairs, where the values can be simple data types (strings, numbers, booleans, etc.) or nested JSON objects or arrays. Traversing this tree requires understanding the structure and having a way to identify and extract the desired data. In the below examples, we will use JSON Data of a sample online Store Catalog containing data of each product in the catalog as shown below:

var catalog = {
    "products": [
        {
            "id": 1,
            "name": "T-shirt",
            "price": 19.99,
            "category": "Clothing",
            "color": "Blue"
        },
        {
            "id": 2,
            "name": "Smartphone",
            "price": 399.99,
            "category": "Electronics",
            "color": "Black"
        },
        {
            "id": 3,
            "name": "Book",
            "price": 9.99,
            "category": "Books",
            "color": "Red"
        }
    ]
};

Importing jQuery

We need to include jQuery in our webpage before starting the search implementation. We can either download the jQuery library and host it locally or include it from a content delivery network (CDN). We will use the CDN method for simplicity.

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <title>JSON Tree Search with jQuery</title>
</head>
<body>
    <!-- Your HTML content here -->
</body>
</html>
</pre>

Searching JSON tree with jQuery

We can use various methods to search for specific data from the JSON tree.Using JQuery we can perform this task using the methods as follows:

Method 1:Basic Search using .each() method

To perform a basic search, we can use the .each() function of jQuery to iterate over each object or array in the JSON tree. For example, let's find all products with a price greater than $15.

Syntax

$.each(collection, callback)

Here, the .each() method iterates over a collection (such as an array or object) and executes a callback function for each item in the collection. The callback function takes two parameters: the index/key and the value of the current item being iterated.

Example

In the below example, The $(document).ready() function ensures that the code inside it executes when the document (HTML) is fully loaded. Within the $(document).ready() function, we have an event handler for the click event of the button with the id showOutputBtn. When this button is clicked, the function is triggered. Inside the click event handler function, we define a variable outputText to store the output string. Then, we use $.each() to iterate over each product object in the catalog.products array. For each product, we check if the price is greater than 15. If it is, we append the product's name to the outputText along with a line break . Finally, we use $('#output').html(outputText) to set the HTML content of the

element with the id output to the outputText. This displays the output on the screen.

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <title>JSON Tree Search with jQuery</title>
</head>
<body>
    <h1>JSON Tree Search with jQuery</h1>
    <p>Click the button to display the output:</p>
    <button id="showOutputBtn">Show Output</button>
    <p id="output"></p>

    <script>
        var catalog = {
            "products": [
                {
                    "id": 1,
                    "name": "T-shirt",
                    "price": 19.99,
                    "category": "Clothing",
                    "color": "Blue"
                },
                {
                    "id": 2,
                    "name": "Smartphone",
                    "price": 399.99,
                    "category": "Electronics",
                    "color": "Black"
                },
                {
                    "id": 3,
                    "name": "Book",
                    "price": 9.99,
                    "category": "Books",
                    "color": "Red"
                }
            ]
        };

        $(document).ready(function() {
            $('#showOutputBtn').click(function() {
                var outputText = '';
                $.each(catalog.products, function(index, product) {
                    if (product.price > 15) {
                        outputText += product.name + '<br>';
                    }
                });
                $('#output').html(outputText);
            });
        });
    </script>
</body>
</html>

Output

Method 2:Filtering by Property using filter and grep Method

To search for specific values within a property, we can use jQuery's .filter() method. For example, let's find all products that belong to the "Electronics" category in the JSON data tree.

Syntax

$.grep(array, callback)

Here, the .grep() method filters an array based on a provided callback function. It creates a new array with only the elements that pass the condition specified in the callback. The callback function should return true to include the element in the filtered array or false to exclude it.

Example

In the below example, we set up a click event handler for the button with the id filterByPropertyBtn. When the button is clicked, it filters the catalog.products array based on the category property, selecting only the products that have a category value of "Clothing". Then, it iterates over the filtered products and appends their names to the outputText variable, separated by line breaks. Finally, it sets the HTML content of the element with the id filterByPropertyOutput to the outputText, displaying the filtered product names on the screen.

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <title>JSON Tree Search with jQuery</title>
</head>
<body>
    <h1>JSON Tree Search with jQuery</h1>
    <p>Filter by Property:</p>
    <button id="filterByPropertyBtn">Filter by Property</button>
    <p id="filterByPropertyOutput"></p>

    <script>
        var catalog = {
            "products": [
                {
                    "id": 1,
                    "name": "T-shirt",
                    "price": 19.99,
                    "category": "Clothing",
                    "color": "Blue"
                },
                {
                    "id": 2,
                    "name": "Smartphone",
                    "price": 399.99,
                    "category": "Electronics",
                    "color": "Black"
                },
                {
                    "id": 3,
                    "name": "Book",
                    "price": 9.99,
                    "category": "Books",
                    "color": "Red"
                }
            ]
        };

        $(document).ready(function() {
            $('#filterByPropertyBtn').click(function() {
                var filteredProducts = $.grep(catalog.products, function(product) {
                    return product.category === "Clothing";
                });

                var outputText = '';
                $.each(filteredProducts, function(index, product) {
                    outputText += product.name + '<br>';
                });
                $('#filterByPropertyOutput').html(outputText);
            });

        });
    </script>
</body>
</html>

Output

Method 3:Using the Deep Tree Traversal and .find() method

Sometimes, we need to search for specific values within nested JSON structures. In such cases, we can use recursive approaches or leverage jQuery's .find() method. For example, let’s find all products that are either blue or red.

Syntax

$(selector).find(filter)

Here, the .find() method is used to search for descendant elements within a selected element(s) based on a filter. It returns a new jQuery object containing the matched elements. The selector parameter represents the parent element(s), and the filter parameter specifies the element(s) to be found within the parent element(s).

Example

In the below example, we define a recursive function, findMatchingProducts, which traverses the JSON tree and checks for the desired property values. If the color property matches "Blue" or "Red", the product is added to the matchingProducts array.

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <title>JSON Tree Search with jQuery</title>
</head>
<body>
    <h1>JSON Tree Search with jQuery</h1>

    <p>Deep Tree Traversal:</p>
    <button id="deepTraversalBtn">Deep Tree Traversal</button>
    <p id="deepTraversalOutput"></p>

    <script>
        var catalog = {
            "products": [
                {
                    "id": 1,
                    "name": "T-shirt",
                    "price": 19.99,
                    "category": "Clothing",
                    "color": "Blue"
                },
                {
                    "id": 2,
                    "name": "Smartphone",
                    "price": 399.99,
                    "category": "Electronics",
                    "color": "Black"
                },
                {
                    "id": 3,
                    "name": "Book",
                    "price": 9.99,
                    "category": "Books",
                    "color": "Red"
                }
            ]
        };

            $('#deepTraversalBtn').click(function() {
                var matchingProducts = [];

                function findMatchingProducts(data) {
                    $.each(data, function(key, value) {
                        if (key === "color" && (value === "Blue" || value === "Red")) {
                            matchingProducts.push(data);
                        } else if (typeof value === "object") {
                            findMatchingProducts(value);
                        }
                    });
                }

                findMatchingProducts(catalog);

                var outputText = '';
                $.each(matchingProducts, function(index, product) {
                    outputText += product.name + '<br>';
                });
                $('#deepTraversalOutput').html(outputText);
            });
    </script>
</body>
</html>

Output

Conclusion

In this article, we discussed how we can search JSON tree with the help of using jQuery's powerful methods and selectors. By utilizing the techniques explained in this article, you can efficiently search and extract specific data from complex JSON structures. jQuery's intuitive syntax and wide adoption make it an excellent choice for handling JSON manipulation and traversal. In this article, we discussed how we can search JSON tree with the help of using jQuery's powerful methods and selectors. By utilizing the techniques explained in this article, you can efficiently search and extract specific data from complex JSON structures. jQuery's intuitive syntax and wide adoption make it an excellent choice for handling JSON manipulation and traversal.

Updated on: 18-Jul-2023

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements