Search code examples
jsonxpathxquerymarklogicmarklogic-8

How to filter JSON document using XQuery?


I have the following JSON document assigned to a variable as $node:

{ "b": "value",
  "c1": 1,
  "c2": 2,
  "d": "",
  "e": ""
}

I don't know how to get each single node. I tried as $node//node(). But not getting each single node. I need to query this JSON document to skip the empty nodes & insert into the Marklogic DB, which is mentioned as below:

{ "b": "value", "c1": 1, "c2": 2 }

I am new to handle JSON document, kindly help.

Thanks in advance.


Solution

  • Not sure if this matches your needs well, but something like this would work:

    let $node := xdmp:unquote('
      { "b": "value",
        "c1": 1,
        "c2": 2,
        "d": "",
        "e": ""
      }
    ')/node()
    return xdmp:to-json(map:new((
      for $property in $node/node()
      where string-length(string($property)) > 0
      return
        map:entry(name($property), data($property))
    )))
    

    HTH!