首页 > 解决方案 > 如何使用xquery从json文件中删除元素

问题描述

我在 MarkLogic 中有一个 .json 文件:

{
  "contextProductIdCDM": {
    "variables": {
      "source": "'Inm'", 
      "source_table_id": "'123'", 
      "Referdate": "normalize-space(string-join((J_MCCC, if(J_MCDC eq '') then '000' else J_MCDC),''))"
    }, 
    "$ref": "#/contexts/Closure"
  }, 
  "predcondition": "xyz=1"
}

我想删除前置条件,也想使用 xquery 删除引用数据的某些部分。任何人都可以帮助如何实现这一目标?

标签: xquerymarklogic

解决方案


如果您想删除该precondition字段并修改该contextProductIdCDM.variables.Referdate值,您可以使用 XPath 处理这些 JSON 属性并使用xdmp:node-delete()xdmp:node-replace()函数:

xquery version "1.0-ml";
let $doc := fn:doc("/test.json")
return (
  xdmp:node-replace($doc/contextProductIdCDM/variables/Referdate, text{ "000" }), 
  xdmp:node-delete($doc/predcondition)
)

如何在 JavaScript 中完成;转换为普通的旧对象,进行修改,然后用更新的 JSON 对象替换文档:

declareUpdate();
const doc = cts.doc("/test.json");
let obj = doc.toObject(); // create mutable representation
obj.contextProductIdCDM.variables.Referdate = '000'; //change the Referdate property value
delete obj.predcondition; // delete precondition field
xdmp.nodeReplace(doc, obj); // update the JSON document with the changes

推荐阅读