JSONHandler writes JSON data

JSONHandler offers a persistent key-value store with an API inspired by Firebase. For example:

url:
    jsonhandler-data:
        pattern: /$YAMLURL/data/(.*)
        handler: JSONHandler
        kwargs:
            # Optional location where JSON data is persisted.
            # (If path is not specified, the JSON data is not persisted.
            #  When Gramex restarts, the data is lost.)
            path: $GRAMEXDATA/jsonhandler.json

            # Optional initial dataset to be used -- used only if path is
            # not specified. (Defaults to null.)
            data: {x: 1}

The examples below use jQuery.ajax and the cookie.js libraries.

GET - read data

You can read data via a GET request:

$.ajax('data/')
// OUTPUT

You can read data from a specific key:

$.ajax('data/y')    // OUTPUT

… or from a sub-key:

$.ajax('data/y/a')  // OUTPUT

Missing keys return null:

$.ajax('data/na')   // OUTPUT

Array values can be accessed via integer path elements:

$.ajax('data/z/0')  // OUTPUT

PUT - write data

You can write JSON data via a PUT request.

$.ajax('data/new', {
  method: 'PUT',
  data: '{"x": 1}'
})  // OUTPUT

This stores the JSON value as-is:

$.ajax('data/new')        // OUTPUT

Incorrect values raise an error:

$.ajax('data/invalid', {
  method: 'PUT',
  data: 'xxx'             // Invalid JSON
})  // OUTPUT

POST - add data

You can add new records via a POST request. First, let’s start with an empty object.

$.ajax('data/list', {method: 'DELETE'})    // OUTPUT

… and POST a record to it.

$.ajax('data/list', {
  method: 'POST',
  data: '{"x": 1}'
})                      // OUTPUT

Records are added with a unique random key. The final dataset looks like this:

$.ajax('data/list')
// OUTPUT

PATCH - update data

You can update existing data via PATCH. For example, the initial data:

$.ajax('data/y')        // OUTPUT

… can be updated via PATCH:

$.ajax('data/y', {
  method: 'PATCH',
  data: '{"c":3}'
})                      // OUTPUT

The result is:

$.ajax('data/y')        // OUTPUT

DELETE - remove data

You can delete any key via DELETE. For example, the initial data:

$.ajax('data/y')        // OUTPUT

… can have keys removed:

$.ajax('data/y/a', {
  method: 'DELETE'
})                      // OUTPUT

The result is:

$.ajax('data/y')        // OUTPUT

Method override

You can use the X-HTTP-Method-Override header to override the method. For example, this is the same as a PUT request:

$.ajax('data/new', {
    method: 'POST',
    headers: {
      'X-HTTP-Method-Override': 'PUT',
    },
    data: '1'
})  // OUTPUT

You an also use the ?x-http-method-override= query parameter:

$.ajax('data/new?x-http-method-override=PUT', {
    method: 'POST',
    data: '1'
})  // OUTPUT

NOTE: The method must be in capitals, e.g. PUT, DELETE, PATCH, etc.