how to delete an element from json file using xquery

Viewed 208

I have a .json file in MarkLogic as :

{
  "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"
}

I want to delete the predcondition and also want to delete some part of referdata also using xquery. Can anyone help how to achieve that?

1 Answers

If you wanted to remove the precondition field and modify the contextProductIdCDM.variables.Referdate value, you could address those JSON properties with XPath and use xdmp:node-delete() and xdmp:node-replace() functions:

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

How it could be done in JavaScript; convert to a plain old object, make the modifications, then replace the document with that updated JSON object:

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
Related