How to search JSON tree with the help of jQuery?

JSON (JavaScript Object Notation) is a data format widely used when transmitting data between servers and web applications. When JSON data has a complex structure, searching for specific data requires special function implementation. jQuery, a popular JavaScript library, provides powerful methods to navigate and search JSON trees efficiently using .each(), filter(), and grep() methods.

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 values can be simple data types (strings, numbers, booleans) or nested JSON objects or arrays. In the examples below, we'll use sample online store catalog data ?

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"
        }
    ]
};

Setting Up jQuery

Include jQuery in your webpage before implementing search functionality. You can 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>

Using .each() Method for Basic Search

The .each() function iterates over each object or array in the JSON tree. Let's find all products with a price greater than $15 ?

Syntax

$.each(collection, callback)

The .each() method iterates over a collection and executes a callback function for each item. The callback receives the index/key and value of the current item.

Example

<!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 products over $15:</p>
    <button id="showOutputBtn">Show Products</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>

Using $.grep() Method for Filtering

To search for specific values within a property, we can use jQuery's $.grep() method. Let's find all products in the "Clothing" category ?

Syntax

$.grep(array, callback)

The $.grep() method filters an array based on a callback function, creating a new array with elements that pass the condition.

Example

<!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 Category:</p>
    <button id="filterByPropertyBtn">Filter Clothing</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>

Using Deep Tree Traversal

For searching within nested JSON structures, we can use recursive approaches. Let's find all products that are either blue or red in color ?

Example

<!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">Find Blue/Red Products</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"
                }
            ]
        };

        $(document).ready(function() {
            $('#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>

Comparison of Methods

Method Use Case Performance
$.each() Basic iteration and filtering Good for simple searches
$.grep() Array filtering based on conditions Efficient for single-level filtering
Recursive traversal Deep nested structure searches More complex but thorough

Conclusion

jQuery provides powerful methods for searching JSON trees effectively. Use $.each() for basic iteration, $.grep() for array filtering, and recursive functions for deep nested searches. These techniques enable efficient data extraction from complex JSON structures.

Updated on: 2026-03-27T08:45:03+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements