如何将逗号放在MarkLogic中生成JSON的正确位置?

Jon*_*Jon 1 xquery marklogic

如果它是最后一项,我试图在大括号后没有逗号.

  for $row in /md:row
  let $test := $row/md:test/text()
  let $last := $row/*[fn:position() = fn:last()]

  return (
   '{
    "test": {
    "type": "test",
    "test": [',$testa,',',$testb,']
    }      
   }',
   if($last)
   then ''
   else (',')
  )
Run Code Online (Sandbox Code Playgroud)

Cha*_*ffy 6

在给定情况下,输出为JSON,请使用json:transform-to-jsonMarkLogic提供的调用.

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

json:transform-to-json(
  <json type="array" xmlns="http://marklogic.com/xdmp/json/basic">{
    for $row in /md:row
    let $test := $row/md:test/text()
    return (
      <json type="object">
        <test type="object">
          <type type="string">test</type>
          <test type="array">
            <item type="string">{$test}</item> <!-- testa and testb were undefined -->
            <item type="string">{$test}</item>
          </test>
        </test>
      </json>
    )
  }</json>
)
Run Code Online (Sandbox Code Playgroud)

这避免了以下问题:

  • 你并不需要添加逗号语法在所有 -他们完全被产生的transform-to-json通话,模拟法庭一整套问题这一点.
  • 无意中输出格式错误(如果您的XML文本节点包含需要转义为在JSON中有效的字符 - 例如,对于换行符也是如此).
  • 注入攻击(如果你$testa或者$testb包含test", "hello", "world", "foo你的JSON代码中你有额外的单独元素;更激进的攻击可以逃脱结构并向你的外部列表添加全新的词典).