RCS RCS - 5 months ago 18
JSON Question

Marklogic - Update within an array of element of a json using java api

Lets say we have json looks like

{
"name":"abc",
"lastName":"xyz",
"description":"aaaaa aaaa",
"dob":11-10-1988,
"workInformation":[
{
"address":"kolkata",
"workFor":"vvv Pvt Ltd",
"reference" : [
{
"refName" : "ttt",
"refId" : "12345"
},
{
"refName" : "sss",
"refId" : "23412"
}
]
},
{
"address":"bangalore",
"workFor":"www Pvt Ltd",
"reference" : [
{
"refName" : "rrr",
"refId" : "43434"
},
{
"refName" : "yyyy",
"refId" : "34213"
}
]
},
{
"address":"delhi",
"workFor":"sss Pvt Ltd",
"reference" : [
{
"refName" : "qqqq",
"refId" : "76767"
},
{
"refName" : "gggg",
"refId" : "65432"
}
]
}
]
}


I have tried insertFragment of DocumentPatchBuilder. Using this i am able to update before/after of the json properties. But i have to insert inside the property workInformation which is of array type. Here is the insertFragment example which i tried -

DocumentPatchBuilder pb = docMgr.newPatchBuilder();
pb.pathLanguage(DocumentPatchBuilder.PathLanguage.JSONPATH);
ObjectMapper mapper = new ObjectMapper();
pb.insertFragment("workInformation", Position.BEFORE,mapper.createObjectNode().put("hello", "hai"));


I wanted to insert data mentioned below inside the workInformation section using java api -

{
"address":"Mumbai",
"workFor":"zzz Pvt Ltd"
}


Please let me know how to do it.

Thanks for Reading.

Answer

To insert inside the workInformation array, you would need to specify the position as POSITION.LAST_CHILD to insert it as the last child of the child list of the context. Also, you would need to specify "workInformation" as an array type in the first argument of patchBuilder.insertFragment - ["workInformation"]. The code would be something like:

DocumentPatchBuilder pb = docMgr.newPatchBuilder();
pb.pathLanguage(DocumentPatchBuilder.PathLanguage.JSONPATH);
ObjectMapper mapper = new ObjectMapper();

ObjectNode fragmentNode = mapper.createObjectNode();
fragmentNode = mapper.createObjectNode();
fragmentNode.put("address", "mumbai");
fragmentNode.put("workFor", "zzz Pvt Ltd");
String fragment = mapper.writeValueAsString(fragmentNode);

pb.insertFragment("$.[\"workInformation\"]", Position.LAST_CHILD, fragment);

This should do the trick and this would insert

{
    "address":"Mumbai", 
    "workFor":"zzz Pvt Ltd"
}

at the end of "workInformation" property.

Comments