Skip to content

0.7 JSON Client API

David Greisen edited this page Aug 25, 2013 · 9 revisions

A list of pull requests and issues:


Introduction

The JSON API is an easy way to manipulate JSON documents. e.g:

// Create some JSON object
var myObject = { todo: 'nothing here' };

// Set the structure of the document to the JSON object
doc.set( myObject );

// Get the document's JSON object
docObject = doc.get(); // => {'todo': 'nothing here'};

// Get the "todo" subdoc - this creates a new context that must be tracked -> use sparingly
todo = doc.getContextAt('todo');

// print out the "todo" subdoc
console.log( todo.get(); ) // => 'nothing here';

// Set the "todo" subdoc to a completely different value
todo.set([]);

// Print out the "todo" subdoc again
console.log( todo.get(); ) // => [];

// Push a value to the "todo" subdoc
todo.push({ item: 'take out the garbage', deadline: '8/14/2021', done: false });

// Print out the "todo" subdoc again
console.log( todo.get() ); // => [{ item: 'take out the garbage', deadline: '8/14/2021', done: false }]

// change the first item text
todo.remove([0, 'item', 13], 7);
todo.insert([0, 'item', 13], 'trash');

// Set the first todo item to done
todo.set([0, 'done'], true);

// Print out the first "todo" 
console.log( todo.get([0]) ); // => { item: 'take out the trash', deadline: '8/14/2021', done: true }

// Get the document JSON object again
doc.get(); // => {'todo':'some string value'};

// Create event when something is inserted into the doc
todo.on('insert', function (pos, item) {
  ...
})
todo.on('child op', function (path, op) {
  var item_idx = path[0]
  console.log("Item "+item_idx+" now reads "+todo.get()[item_idx])
  if (op.si != undefined) {
    // ...
  } else if (op.sd != undefined) {
    // ...
  }
})

// IMPORTANT: remove the todo context when we are done with it
todo.destroy();

A note on paths

Whenever you perform an operation on the JSON object, like inserting into a list, or removing a part of a string, you must specify where within the JSON object the operation should be applied. Locations within a JSON object are uniquely identified by a path consisting of an array of hash keys, and string and array indices. For example, given the following object:

obj = {
  a: 'w',
  b: {
    i: 'x',
    ii: [
      'y',
      'zebra'
    ]
  }
}
  • path ['a'] corresponds to 'w',
  • path ['b', 'i']) corresponds to 'x',
  • path ['b', 'ii', 1] corresponds to 'zebra', and
  • path ['b', 'ii', 1, 2] corresponds to 'b' (the 'b' in 'zebra')

Nearly every method accepts a path argument. However, often, you may wish to perform many operations on a small subset deep within the JSON document. Repeatedly entering nearly the same 20-length array would be tiresome and error-prone. Instead, you can create a new context at a path. Now, all path arguments will be relative to the location corresponding to the context. If a path argument isn't given, the operation will be applied to the location corresponding to the context.

Contexts need machinery to keep themselves pointing at the correct location within the JSON object as the object changes. To prevent memory leaks you must call context.destroy() when you are done with a context to prevent memory leaks.

Methods

  • doc.getContextAt(path...)

    Returns a sub-document starting at path. For the document itself, use doc.getContextAt(). doc.getContextAt can also accept an array as its only argument.

  • subdoc.get([path])

    Returns the snapshot located at path.

  • subdoc.getLength([path]) (Lists and Strings only)

    Get the length of the list or string

  • subdoc.set([path], value, callback)

    Sets the document at subdoc, or at the optional path if specified, to value.

  • subdoc.insert(path, data, callback) (Strings and lists only)

    Inserts data at path in the string or list. The item at path (and everything after it) is pushed forward.

  • subdoc.remove([path], [length], callback)

    Removes the object at path from the tree. If the optional length is included (strings and lists only) it will remove the range from path to path+length from the list or string.

  • subdoc.push([path], item, callback) (Lists only)

    Inserts item at the end of the list.

  • subdoc.move([path], to, callback) (Lists only)

    Causes the item at path to have the index to.

  • subdoc.add([path], amount, callback) (Numbers only)

    Adds amount to the number.

  • removeListener(l)

    subdoc = doc.at(...)
    l = subdoc.on('insert', ...)
    subdoc.removeListener(l)
    // doc.removeListener(l) also works.

Events

Subscribing to an event with subdoc.on returns a listener object. Unsubscribe from the event by passing the listener returned by subdoc.on to subdoc.removeListener(listener). Thus, to add and remove a listener to the insert event:

var listener = subdoc.on('insert', function (position, data) { ... });
subdoc.removeListener(lister);
  • insert

    subdoc.on('insert', function (position, data) { ... })

    (Strings and lists) Emitted when a remote client inserts an item into the list, or inserts text into the string. Call subdoc.get() to get the new value.

  • delete

    subdoc.on('delete', function (position, data) { ... })

    (Strings and lists) Emitted when a remote client removes an item from the list, or deletes text from the string. data contains the item or text that was removed.

  • replace

    subdoc.on('replace', function (position, was, now) { ... })

    (Lists and objects) Emitted when a remote client replaces an element of an object or list. position is the index of the array or the key of the object.

  • move

    subdoc.on('move', function (from, to) { ... })

    (Lists only) Emitted when a remote client moves an element in the list from from to to.

  • add

    subdoc.on('add', function (amount) { ... })

    (Numbers only) Emitted when a remote client adds amount to the number.

  • child op

    subdoc.on('child op', function (path, op) { ... })

    Emitted when a remote operation changes any element contained in subdoc. path is the path below this document, such that subdoc.get()[path[0]][path[1]][...][path[path.length-2]] is the affected element, and path[path.length-1] is the index into that element (except for na operations, in which case there is no index). op is the raw operation that was applied. See JSON Operations for details.

Clone this wiki locally