Val
Val

Reputation: 15

How to insert an object into a JSON array in Javascript?

I am trying to insert a new item(json) in an array using JavaScript.

I don't want to use xdmp.nodeReplace to replace the array because it could be too big in memory (not for this sample but with real data).

'use strict';

declareUpdate();

xdmp.documentInsert("/test/items.json" , { result: [{"name": "name0"," ref": "000"}]});

let item1 = {"name": "name1"," ref": "111"};
var n1 = new NodeBuilder();
var newNode1 = n1.addNode(item1);

var parentNode = cts.doc("/test/items.json"); 
var resultNode = parentNode.xpath("/result");
xdmp.nodeInsertChild(resultNode, newNode1.toNode());
//[javascript] XDMP-CHILDUNNAMED: //xdmp.nodeInsertChild(Sequence(xdmp.unpath("fn:doc('/test/items.json')/array-node('result')/object-node()")), ObjectNode({"name":"name1", " ref":"111"})) 
//-- Object nodes cannot have unnamed children

// I also tried 
//xdmp.nodeInsertChild(resultNode, newNode1);
//[javascript] XDMP-ARGTYPE: xdmp.nodeInsertChild(Sequence(xdmp.unpath("fn:doc('/test/items.json')/array-node('result')/object-node()")), [object NodeBuilder]) 
//  -- arg2 is not of type Node

I am expecting to have in "/test/items.json":

{ result: [{"name": "name0"," ref": "000"}, {"name": "name1"," ref": "111"}]}

Upvotes: 1

Views: 125

Answers (1)

This comes down to the selector. See Traversing JSON Documents Using XPath For details.

You need to select the array-node() itself and not the content.

If You replace 1 line in your sample you get what I believe is the desired result.

FROM:

var resultNode = parentNode.xpath("/result");

TO:

var resultNode = parentNode.xpath("/array-node(\"result\")");

Upvotes: 1

Related Questions