如何使用 jQuery 搜尋 JSON 樹?


JSON (JavaScript 物件表示法) 是一種在伺服器和 Web 應用程式之間傳輸資料時廣泛使用的資料格式。在許多情況下,JSON 資料具有複雜的結構,搜尋特定資料需要一些特殊的函式實現。jQuery 是一款流行的 JavaScript 庫,它提供強大的方法,可以使用 .each() 方法、filter() 方法和 grep 方法高效地導航和搜尋 JSON 樹。在本文中,我們將探討所有這些方法,以便藉助 jQuery 搜尋 JSON 樹。

理解 JSON 樹

JSON 資料以分層結構組織,通常稱為 JSON 樹。它由鍵值對組成,其中值可以是簡單資料型別(字串、數字、布林值等)或巢狀的 JSON 物件或陣列。遍歷此樹需要理解其結構並找到一種方法來識別和提取所需資料。在下面的示例中,我們將使用示例線上商店目錄的 JSON 資料,其中包含目錄中每個產品的如下所示的資料

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

匯入 jQuery

在開始搜尋實現之前,我們需要在網頁中包含 jQuery。我們可以下載 jQuery 庫並將其本地託管,也可以從內容分發網路 (CDN) 包含它。為簡便起見,我們將使用 CDN 方法。

<!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>

使用 jQuery 搜尋 JSON 樹

我們可以使用多種方法從 JSON 樹中搜索特定資料。使用 jQuery,我們可以使用如下方法執行此任務

方法 1:使用 .each() 方法進行基本搜尋

要執行基本搜尋,我們可以使用 jQuery 的 .each() 函式迭代 JSON 樹中的每個物件或陣列。例如,讓我們查找價格大於 $15 的所有產品。

語法

$.each(collection, callback)

在這裡,.each() 方法迭代集合(例如陣列或物件),併為集合中的每個專案執行回撥函式。回撥函式接受兩個引數:正在迭代的當前專案的索引/鍵及其值。

示例

在下面的示例中,$(document).ready() 函式確保其中的程式碼在文件 (HTML) 完全載入後執行。$(document).ready() 函式內,我們有一個針對 id 為 showOutputBtn 的按鈕的 click 事件的事件處理程式。單擊此按鈕時,將觸發該函式。在 click 事件處理程式函式內,我們定義一個變數 outputText 來儲存輸出字串。然後,我們使用 $.each() 迭代 catalog.products 陣列中的每個產品物件。對於每個產品,我們檢查價格是否大於 15。如果是,我們將產品的名稱附加到 outputText 中,並新增換行符。最後,我們使用 $('#output').html(outputText) 將 id 為 output 的元素的 HTML 內容設定為 outputText。這將在螢幕上顯示輸出。

元素的 id 為 output,設定為 outputText。這將在螢幕上顯示輸出。

<!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>

輸出

方法 2:使用 filter 和 grep 方法按屬性過濾

要搜尋屬性內的特定值,我們可以使用 jQuery 的 .filter() 方法。例如,讓我們查詢 JSON 資料樹中屬於“電子產品”類別的所有產品。

語法

$.grep(array, callback)

在這裡,.grep() 方法根據提供的回撥函式過濾陣列。它建立一個新陣列,其中只包含透過回撥函式中指定條件的元素。回撥函式應返回 true 以將元素包含在已過濾的陣列中,或返回 false 以將其排除。

示例

在下面的示例中,我們為 id 為 filterByPropertyBtn 的按鈕設定了一個 click 事件處理程式。單擊該按鈕時,它會根據 category 屬性過濾 catalog.products 陣列,只選擇 category 值為“服裝”的產品。然後,它迭代已過濾的產品並將它們的名字附加到 outputText 變數中,並用換行符分隔。最後,它將 id 為 filterByPropertyOutput 的元素的 HTML 內容設定為 outputText,在螢幕上顯示已過濾的產品名稱。

<!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>

輸出

方法 3:使用深度樹遍歷和 .find() 方法

有時,我們需要搜尋巢狀 JSON 結構中的特定值。在這種情況下,我們可以使用遞迴方法或利用 jQuery 的 .find() 方法。例如,讓我們查詢所有藍色或紅色的產品。

語法

$(selector).find(filter)

在這裡,.find() 方法用於根據過濾器搜尋所選元素中的後代元素。它返回一個新的 jQuery 物件,其中包含匹配的元素。selector 引數表示父元素,filter 引數指定要在父元素中查詢的元素。

示例

在下面的示例中,我們定義了一個遞迴函式 findMatchingProducts,它遍歷 JSON 樹並檢查所需的屬性值。如果 color 屬性匹配“藍色”或“紅色”,則將產品新增到 matchingProducts 陣列中。

<!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>

輸出

結論

在本文中,我們討論瞭如何使用 jQuery 的強大方法和選擇器來搜尋 JSON 樹。透過利用本文中解釋的技術,您可以高效地搜尋和提取複雜 JSON 結構中的特定資料。jQuery 的直觀語法和廣泛採用使其成為處理 JSON 操作和遍歷的絕佳選擇。在本文中,我們討論瞭如何使用 jQuery 的強大方法和選擇器來搜尋 JSON 樹。透過利用本文中解釋的技術,您可以高效地搜尋和提取複雜 JSON 結構中的特定資料。jQuery 的直觀語法和廣泛採用使其成為處理 JSON 操作和遍歷的絕佳選擇。

更新於:2023年7月18日

871 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告