Search code examples
jsonxquerymarklogic

I want to write the XQuery to print the specific keys in JSON


This is my sample JSON

{
"id":"743",
"groupName":"group1",
"transation":{
    "101":"success",
    "102":"rejected",
    "301":"processing"
     }
}

Expected Result:

"101"
"102"
"301"

Can anyone please help me to print the above result using XQuery?

I can achieve this through JavaScript, but I need to write in XQuery.


Solution

  • Not knowing how you are reading the JSON document, whether as a doc in the database or parsing a JSON string, below uses xdmp:unquote() to parse a string, but you could instead just read the document from the database with fn:doc() or through cts:search().

    Then, you could just XPath to the transation fields and return those node names with the name() function:

    let $jsonData := xdmp:unquote('
    {
    "id":"743",
    "groupName":"group1",
    "transation":{
        "101":"success",
        "102":"rejected",
        "301":"processing"
         }
    }')
    return 
      $jsonData/transation/*/name()