Mehul
Mehul

Reputation: 178

How to insert lines into a JSON document in MarkLogic [Update]

I have a JSON document with say fields A,B,C. I want to add fields D,E,F to it. How do I add/concat them? I'm using a cts.uris to first search for the right document to update and once I have that as a sequence then I'm converting it to an object for processing. I know how to update a particular field by not how to add new lines in it. I'm coding in JavaScript in the query console.

Upvotes: 0

Views: 298

Answers (2)

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16795

You can do the following steps to update a json document:

declareUpdate();
// get the document
const uri = '/folder/doc.json';
const doc = cts.doc(uri);

// create an object from the document
const obj = doc.toObject();

// add the new fields to the object
obj.d = 'd';
obj.e = 'e';
obj.f = 'f';

// save the object as a json document
xdmp.documentInsert(uri, obj);

Upvotes: 3

loicnestler
loicnestler

Reputation: 527

You can add a property to a JSON object by assigning a value to the belonging key.

const obj = {
  a: true,
  b: 42,
  c: 'Hello World!'
}

obj['d'] = 'To be, or not to be'
obj['e'] = 'foobar'
obj['f'] = false

console.log(obj)

Upvotes: 1

Related Questions