問題描述
如何使用 xdmp:node‑insert 在 Marklogic 的 JSON 文檔中插入節點 (how to insert node in JSON doc in Marklogic using xdmp:node‑insert)
我想像這樣在 JSON 文檔中插入節點:
{ “fileName”:“l”,“user_id”:“test”,“requestId”:“ 1232”,“feedbackType”:“cpd_mah” }
運行此代碼:
let $old := $doc/filename
return
xdmp:node‑insert‑after($old, object‑node{"isSaved": ""})
但這會引發錯誤XDMP‑CHILDUNNAMED。
參考解法
方法 1:
I agree with Mads, that using node‑insert‑child makes more sense with JSON. You can use node‑insert‑after though. Your attempt is throwing an XDMP‑CHILDUNNAMED
error because you are passing in an unnamed object node (which is basically an anonymous wrapper for its properties), rather than the named property you'd like to insert. Mads code is giving away how you can make it work:
let $old := doc("/test.json")/filename
return
xdmp:node‑insert‑after($old, object‑node{"isSaved": ""}/isSaved)
Note: if you run it multiple times, it will replace rather than insert, since properties should be unique.
HTH!
方法 2:
JSON properties don't have the concept of a sibling, the way that XML elements do.
A JSON object is basically a map with a set of properties. So, rather than inserting an object as a child node after one of the properties, you want to insert a child node (notice the XPath selecting isSaved
from the constructed object) of the JSON document object‑node()
let $old := doc("/test.json")/object‑node()
return
xdmp:node‑insert‑child($old, object‑node{"isSaved": ""}/isSaved)
A few examples of working with JSON in XQuery from the MarkLogic documentation: https://docs.marklogic.com/guide/app‑dev/json#id_60123
(by KumarG、grtjn、Mads Hansen)