【问题标题】:Serialize JSON with indentation from XQuery使用来自 XQuery 的缩进序列化 JSON
【发布时间】:2018-06-28 08:48:12
【问题描述】:

通过 MarkLogic 上的 XQuery,是否可以序列化带有缩进的 JSON 节点?

可以使用xdmp:quote() 对 XML 执行此操作,但对 JSON 节点使用相同的代码会返回一个长而扁平的字符串,没有缩进。

【问题讨论】:

  • 我不确定 MarkLogic 是否采用了 XQuery 3.1 的 JSON 序列化方法,但如果是,调用 serialize($my-json, map { "method": "json", "indent": true() }) 就可以了。

标签: json xquery marklogic


【解决方案1】:

我还有一个函数,可以用 XQuery 漂亮地打印 JSON。它最初来自 from here,但我已经对其进行了许多错误修复和增强:

declare namespace pp = "http://marklogic.com/ns/prettyprint";

declare function pp:pretty-print($str as xs:string) as xs:string {
  let $s1 := fn:replace($str,'(\{|\(|\[)','$1
')
  let $s2 := fn:replace($s1,'(\}|\)|\])','
$1')
  let $s3 := fn:replace($s2,',',',
')
  let $tokens := fn:tokenize($s3,'
')
  let $map := map:new((map:entry("index",0),map:entry("buffer","")))
  let $_ := 
    for $token in $tokens return 
      (
      for $new-index in (0 to map:get($map,"index")-1) 
      return 
          if ($new-index eq map:get($map,"index")-1 and fn:matches($token,'[\}]')) then () else map:put($map,"buffer",map:get($map,"buffer")||"	"),
          map:put($map,"buffer",map:get($map,"buffer")||fn:normalize-space($token)||'
'),
          if (fn:matches($token,'[\{|\(|\[]')) then 
            map:put($map,"index",map:get($map,"index") + 1)
          else if (fn:matches($token,'[\)|\]]')) then  
            map:put($map,"index",map:get($map,"index") - 1)
          else if (fn:matches($token,'[\}]')) then  
            map:put($map,"index",map:get($map,"index") - 1)
          else () 
      )
   return map:get($map,"buffer")
};

【讨论】:

    【解决方案2】:

    我尝试了几种不同的方法,但似乎只有一个自定义函数可以解决问题:

    xquery version "1.0-ml";
    
    declare namespace fx = "http://www.functx.com";
    declare function fx:repeat-string
      ( $stringToRepeat as xs:string? ,
        $count as xs:integer )  as xs:string {
    
       string-join((for $i in 1 to $count return $stringToRepeat),
                            '')
     } ;
    
    declare function local:stringify($nodes, $indent) {
      local:stringify($nodes, $indent, 0)
    };
    
    declare function local:stringify($nodes, $indent, $level) {
      let $indent-string := fx:repeat-string(" ", $indent * $level)
      for $node in $nodes
      return (
        $indent-string
        || (
          if (name($node) != "" and not($node/.. instance of array-node())) then
            (""" || name($node) || "": ")
          else ""
        ) || (
          typeswitch ($node)
          case object-node() return (
            "{
" || string-join(local:stringify($node/node(), $indent, $level + 1), ",
") || "
" || $indent-string || "}"
          )
          case array-node() return (
            "[
" || string-join(local:stringify($node/node(), $indent, $level + 1), ",
") || "
" || $indent-string || "]"
          )
          case text() return (
            """ || replace(replace(replace($node, "
", "\\n"), "
", "\\r"), """, '\\"') || """
          )
          default return xdmp:quote($node)
        )
      )
    };
    
    let $json := object-node{
      "text": "abc",
      "number": 1,
      "boolean": true(),
      "null": null-node{},
      "array": array-node{
        "abc",
        1,
        true(),
        null-node{},
        object-node{ "foo": "bar

"'mitswa" }
      },
      "object": object-node{
        "text": "abc",
        "number": 1,
        "boolean": true(),
        "null": null-node{},
        "array": array-node{
          "abc",
          1,
          true(),
          null-node{},
          object-node{ "foo": "bar" }
        }
      }
    }
    return (
      xdmp:quote($json, map:entry("indentUntyped", "yes")),
      xdmp:to-json-string($json),
      xdmp:javascript-eval("JSON.stringify(json, null, 2);", map:entry("json", $json)),
      local:stringify($json, 2)
    )
    

    HTH!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-02
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      相关资源
      最近更新 更多