Master XQuery: Extracting Specific Keys from JSON Data

Blessings Photo

Blessings
3 weeks 1 Views
Category:
Description:

Learn how to efficiently use XQuery to print specific keys from JSON data, breaking down the steps to achieve your desired results ...

To extract specific keys from JSON data using XQuery, you can use the json-to-xml function available in XQuery 3.1 and later. This allows you to convert JSON into an XML format, from which you can easily extract the desired keys.

Example JSON Data

Assuming you have the following JSON data:

json
{
    "fruits": [
        {"name": "Apple", "color": "Red"},
        {"name": "Banana", "color": "Yellow"},
        {"name": "Orange", "color": "Orange"}
    ],
    "vegetables": [
        {"name": "Carrot", "color": "Orange"},
        {"name": "Broccoli", "color": "Green"}
    ]
}

Step 1: Convert JSON to XML

First, you need to convert the JSON data into XML format:

xquery
let $json := '{
    "fruits": [
        {"name": "Apple", "color": "Red"},
        {"name": "Banana", "color": "Yellow"},
        {"name": "Orange", "color": "Orange"}
    ],
    "vegetables": [
        {"name": "Carrot", "color": "Orange"},
        {"name": "Broccoli", "color": "Green"}
    ]
}'

let $xml := json-to-xml($json)

Step 2: Extract Specific Keys

Now, you can extract specific keys from the converted XML. For example, to extract the names of all fruits:

xquery
return
    <fruit-names>
        {
            for $fruit in $xml/fruits/item
            return
                <name>{ $fruit/name/text() }</name>
        }
    </fruit-names>

Full Example

Here’s the complete XQuery:

xquery
let $json := '{
    "fruits": [
        {"name": "Apple", "color": "Red"},
        {"name": "Banana", "color": "Yellow"},
        {"name": "Orange", "color": "Orange"}
    ],
    "vegetables": [
        {"name": "Carrot", "color": "Orange"},
        {"name": "Broccoli", "color": "Green"}
    ]
}'

let $xml := json-to-xml($json)

return
    <fruit-names>
        {
            for $fruit in $xml/fruits/item
            return
                <name>{ $fruit/name/text() }</name>
        }
    </fruit-names>

Explanation

  1. Convert JSON: The json-to-xml function transforms the JSON string into XML.
  2. Loop Through Fruits: The for loop iterates over each fruit item.
  3. Extract Names: The <name> element is created for each fruit, containing the name extracted from the XML.

Conclusion

This method allows you to effectively extract specific keys from JSON data using XQuery by first converting it to XML, making it easy to navigate and retrieve the desired information.