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

时间:2017-03-15 18:50:12

标签: 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 (',')
  )

3 个答案:

答案 0 :(得分:6)

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

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>
)

这避免了这些问题:

  • 您根本不需要添加语法逗号 - 它们完全由transform-to-json调用生成,扼杀了整套问题。
  • 无意中输出格式错误(如果您的XML文本节点包含需要转义为在JSON中有效的字符 - 例如,对于换行符也是如此)。
  • 注入攻击(如果您的$testa$testb包含test", "hello", "world", "foo,则您的JSON代码中会有额外的单独元素;更具侵略性的攻击可能会逃脱结构并完全添加新词典到你的外部名单)。

答案 1 :(得分:2)

不要检测最后一个元素并在循环中处理它,而是使用string-join,它会自动执行您想要的操作:

string-join(
  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,']
  },
", ")   

答案 2 :(得分:0)

我完全同意Charles的评论,我更喜欢wst的字符串连接,但为了完整起见,还有at语句属于FLWOR表达式。你可以使用这样的东西:

  let $rows := (1 to 10)
  let $last := fn:count($rows)
  for $row at $index in $rows
  let $test := string($row)

  return (
   '{
    "test": {
    "type": "test",
    "test": [',$test,']
    }      
   }',
   if($index eq $last)
   then ''
   else (',')
  )

HTH!

相关问题