Add new key-value pair to JSON created using object-node constructor

235 Views Asked by At

I want to add a new key-value pair to JSON created using object-node constructor.

Object node:

object-node {
     "status": "success",
     "categories": "cat"
  }

XQuery code to insert new pair:

let $outputJson :=
      object-node {
        "status": "success",
        "categories": "cat"
      }
return ( map:put($outputJson, "str", "xyz"), $outputJson )

The above expression fails. Is there a way to insert a new pair?

2

There are 2 best solutions below

1
On

It is annoying that the object-node() can't be manipulated as you might expect, but the object-node() is not mutable.

Instead use json:object(), which will provide a specialized mutable map:

let $outputJson :=
      json:object() 
      => map:with("status", "success") 
      => map:with("categories", "cat")
      
return ( map:put($outputJson, 'str', 'xyz'), $outputJson )
0
On

It probably makes more sense to start off with json:object when constructing json docs dynamically, but in case you need to pull json from the database, and manipulate that, this might be a useful trick:

let $outputJson :=
      object-node {
        "status": "success",
        "categories": "cat"
      }
return xdmp:to-json(map:with(xdmp:from-json($outputJson), "str", "xyz"))

HTH!