Search code examples
xquerymarklogic-10

I want to write the XQuery to print the specific keys in JSON and want to except if it has an array value


I want to write the XQuery to print the specific keys in JSON and want to except if it has an array value.

Sample JSON:

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

Expected Result:

id

groupName

Solution

  • Assuming that you are reading a JSON document from the database, you could iterate over the object property nodes and filter out the object/array properties by testing whether the property has child nodes:

    for $property in  doc("/test.json")/object-node()/node()
    where not($property/node())
    return $property/name() 
    

    Or you could exclude those that are instance of object-node() or array-node()

    for $property in  doc("/test.json")/object-node()/node()
    where not($property instance of object-node() or $property instance of array-node())
    return $property/name()