How to write code that works with JSON API differences in MarkLogic 7 and 8?

MarkLogic 8 improves JSON support in many ways, but some MarkLogic 7 JSON features now have different signatures or do different things. How can I write XQuery code that works with both versions?

+4
source share
1 answer

So far, the main changes that I have encountered are xdmp:from-json, xdmp:to-jsonand json:transfrom-to-json. If you have a fair amount of Markson Logic 7 JSON code, these changes may break existing code.

Instead of directly calling these functions xdmpand json, import this library module and call c:from-json, etc. This allows code written for MarkLogic 7 to be used in both releases.

module namespace c="http://blakeley.com/marklogic/json/compatibility";

import module namespace json="http://marklogic.com/xdmp/json"
 at "/MarkLogic/json/json.xqy";

(: No prefix for the fn:* functions :)
declare default function namespace "http://www.w3.org/2005/xpath-functions";

declare variable $VERSION := xs:integer(
  substring-before(xdmp:version(), ".")) ;

declare function c:from-json(
  $arg as xs:string)
as item()*
{
  xdmp:from-json(
    if ($VERSION ge 8) then xdmp:unquote($arg, (), "format-json")
    else $arg)
};

declare function c:to-json(
  $item as item()*)
as xs:string*
{
  if ($VERSION ge 8) then xdmp:quote($item)
  else xdmp:to-json($item)
};

declare function c:transform-to-json(
  $node as node(),
  $config as map:map?)
as xs:string
{
  json:transform-to-json($node, $config) ! (
    if ($VERSION ge 8) then xdmp:quote(.)
    else .)
};

declare function c:transform-to-json(
  $node as node())
as xs:string
{
  c:transform-to-json($node, ())
};

I will continue this when I encounter other changes or hear about them. If it is too long, I will translate it into a gistub or github project.

+4
source

All Articles