2

I want to insert node in a JSON document like this:

{ "fileName": "l", "user_id": "test", "requestId": "1232", "feedbackType": "cpd_mah" }

Running this code:

let $old := $doc/filename
return
  xdmp:node-insert-after($old, object-node{"isSaved": ""})

but this is throwing an error XDMP-CHILDUNNAMED.

Dave Cassel
  • 8,352
  • 20
  • 38
KumarG
  • 61
  • 1

2 Answers2

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!

grtjn
  • 20,254
  • 1
  • 24
  • 35
0

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

Mads Hansen
  • 63,927
  • 12
  • 112
  • 147