‘jsondata.jsonpatch’ - Module

The emphasis of the design combines low resource requirement with features designed for the application of large filters onto large JSON based data structures.

The patch list itself is defined by RFC6902 as a JSON array. The entries could be either constructed in-memory, or imported from a persistent storage. The export feature provides for the persistent storage of a modified patch list for later reuse.

The module contains the following classes:

  • JSONPatch:
    The controller for the application of patches on in-memory data structures provided by the package ‘json’.
  • JSONPatchItem:
    Representation of one patch entry in accordance to RFC6902.
  • JSONPatchItemRaw:
    Representation of one patch entry read as a raw entry in accordance to RFC6902.
  • JSONPatchFilter:
    Selection filter for the application on the current patch list entries JSONPatchItem.
  • JSONDataPatchError:
    Specific exception for this module.

The address of the the provided ‘path’ components for the entries are managed by the class JSONPointer in accordance to RFC6901.

Module

The JSONPatch module provides for the alteration of JSON data compliant to RFC6902.

Constansts

Operations RFC-6902

Standard operations in accordance to RFC6902. These are represented by the class JSONPatchItem.

  • RFC6902_ADD(1)

    { "op": "add", "path": <rfc6901-string>, "value": <json-node> }
    
  • RFC6902_COPY(2)

    { "op": "copy", "from": <rfc6901-string>, "path": <json-node> }
    
  • RFC6902_MOVE(3)

    { "op": "move", "from": <rfc6901-string>, "path": <json-node> }
    
  • RFC6902_REMOVE(4)

    { "op": "remove", "path": <rfc6901-string> }
    
  • RFC6902_REPLACE(5)

    { "op": "replace", "path": <rfc6901-string>, "value": <json-node> }
    
  • RFC6902_TEST(6)

    { "op": "test", "path": <rfc6901-string>, "value": <json-node> }
    

See JSONPatchItem.

Functions

getOp

jsondata.jsonpatch.getOp(x)[source]

Converts input into corresponding enumeration.

JSONPatch

class jsondata.jsonpatch.JSONPatch(p=None, **kargs)[source]

Representation of a JSONPatch task list for RFC6902.

Contains the defined methods from standards:

  • add
  • remove
  • replace
  • move
  • copy
  • test
Attributes:
patch:
List of patch items.

Attributes

  • JSONPatch.data: JSONPatch object data tree.

Methods

__init__

JSONPatch.__init__(p=None, **kargs)[source]

List of patch tasks.

Args:
p:

Patch list.

p := (
     JSONPatch
   | <list-of-patch-items>
)
kargs:
replace:

Replace masked characters in target specification.

replace := (
     True    # replaces rfc6901 escape sequences: ~0 and ~1
   | False   # omit unescaping
)

Note

Match operations are proceeded literally, thus the escaped characters should be consistent, see rfc6901, Section 3.

default := False

Returns:
self.
Raises:
pass-through

__str__

JSONPatch.__str__()[source]

Prints the display format.

__repr__

JSONPatch.__repr__()[source]

Prints the representation format of a JSON patch list.

apply

JSONPatch.apply(jsondata, **kargs)[source]

Applies the JSONPatch task.

Args:
jsondata:
JSON data the joblist has to be applied on.
Returns:

Returns a tuple of:

(n, lerr): 

n:    number of present active entries
lerr: list of failed entries
Raises:
JSONDataPatchError:

getpatchitem

JSONPatch.getpatchitem(x=None)[source]

Gets the reference to a single patch item.

Args:
x:

Requested item.

x := (
     int
   | JSONPatchItem
) 

int:           index of patch item
JSONPatchItem: the reference to the patch item
Returns:
The selected patch item.
Raises:
None

getpatchitems

JSONPatch.getpatchitems(*args, **kargs)[source]

Gets a list of references of patch items.

Args:
args:

Requested items.

*args := (
   <item>
   | <item-list>
   | None
)
item-list := <item>[, <item-list>]
item := (
     int
   | JSONPatchItem
)
None := "all items of the current patch list"

int:           index of patch item
JSONPatchItem: the reference to the patch item
kargs:
idxlist:

Print with index:

idxlist := (
     True     # format: [{<index>: <JSONPatchItem>}]
   | False    # format: [<JSONPatchItem>]
)
copydata:

Creates a copy of each resulting item.

copydata := (C_DEEP | C_SHALLOW | C_REF)

default := C_REF # no copy

Returns:
A list of the selected patch items.
Raises:
None

gettree

JSONPatch.gettree(*args, **kargs)[source]

Gets the resulting logical JSON data structure constructed from the patch items of the current set.

Args:
args:

Requested items.

*args := (
   <item>
   | <item-list>
   | None
)
item-list := <item>[, <item-list>]
item := (
     int
   | JSONPatchItem
)
None := "all items of the current patch list"

int:           index of patch item
JSONPatchItem: the reference to the patch item
kargs:
data:

An optional JSON data structure, when provided the actual data as selected by the patch list is returned. Else the paths only.

default := None

scope:

Defines the source scope of the data structure.

scope := (
     "in"   # input data, e.g. source for "copy"
   | "out"  # output data, e.g. target for "copy
)

default := “out”

Returns:
The combined list of the selected patch items contained in an object JSONData.
Raises:
None

patch_export

JSONPatch.patch_export(patchfile, schema=None, **kargs)[source]

Exports the current task list.

Args:
patchfile:
JSON patch for export.
schema:
JSON-Schema for validation of the patch list.
kargs:
validator: [default, draft3, off, ]

Sets schema validator for the data file. The values are:

default = validate
draft3  = Draft3Validator
off     = None

default:= validate

pretty:
If True exports as tree format, else all as one line.
Returns:
When successful returns ‘True’, else raises an exception.
Raises:
JSONDataPatchError:

patch_import

JSONPatch.patch_import(patchfile, schemafile=None, **kargs)[source]

Imports a task list.

Args:
patchfile:
JSON patch filename containing the list of patch operations.
schemafile:
JSON-Schema filename for validation of the patch list.
kargs:
replace:

Replace masked characters in target specification.

replace := (
     True    # replaces rfc6901 escape sequences: ~0 and ~1
   | False   # omit unescaping
)

Note

Match operations are proceeded literally, thus the escaped characters should be consistent, see rfc6901, Section 3.

default := False

validator:

Sets schema validator for the data file. Curren release relies on jsonschema, which supports at the time of writing draft-03 and draft-04.

The values are:

validator := (
      MS_DRAFT3           | 'draft3'
    | MS_DRAFT4           | 'draft4'
    | MS_ON               | 'on'
    | MS_OFF              | 'off'
    | MODE_SCHEMA_DEFAULT | 'default'
)

default:= MS_OFF

Returns:
When successful returns ‘True’, else raises an exception.
Raises:
JSONDataPatchError:

repr_export

JSONPatch.repr_export()[source]

Prints the export representation format of a JSON patch list.

str_export

JSONPatch.str_export()[source]

Pretty prints the export representation format of a JSON patch list.

Operators

‘()’

JSONPatch.__call__(jdata, x=None)[source]

Evaluates the related task for the provided index.

Args:
x:
Task index.
jdata:
JSON data the task has to be applied on.
Returns:

Returns a tuple of:

(n, lerr): 

n:    number of present active entries
lerr: list of failed entries
Raises:
JSONDataPatchError:

‘[]’

JSONPatch.__getitem__(key)[source]

Support of slices, for ‘iterator’ refer to self.__iter__.

  1. self[key]
  2. self[i:j:k]
  3. x in self
  4. for x in self

‘S+x’

JSONPatch.__add__(x=None)[source]

Creates and adds patch job to the task queue.

Args:
x:
Extension of pathc job, eithe a JSONPatch, or a JSONPatchItem.
Returns:
Returns a patch job, or raises Exception.
Raises:
JSONDataPatchError

‘S==x’

JSONPatch.__eq__(x)[source]

Compares this pointer with x.

Args:
x:
A valid Pointer.
Returns:
True or False
Raises:
JSONPointerError

‘S+=x’

JSONPatch.__iadd__(x=None)[source]

Adds patch jobs to the task queue in place.

‘S-=x’

JSONPatch.__isub__(x)[source]

Removes the patch job from the task queue in place.

Removes one of the following type(x) variants:

int:
The patch job with given index.
JSONPatchItem:
The first matching entry from the task queue.
Args:
x:

Item to be removed.

x := (
     int
   | JSONPatchItem
) 
Returns:
Returns resulting list without x.
Raises:
JSONDataPatchError:

‘S!=x’

JSONPatch.__ne__(x)[source]

Compares this pointer with x.

Args:
x:
A valid Pointer.
Returns:
True or False
Raises:
JSONPointerError

‘S-x’

JSONPatch.__sub__(x)[source]

Removes the patch job from the task queue.

Removes one of the following type(x) variants:

int:
The patch job with given index.
JSONPatchItem:
The first matching entry from the task queue.
Args:
x:

Item to be removed.

x := (
     int
   | JSONPatchItem
) 
Returns:
Returns resulting list without x.
Raises:
JSONDataPatchError:

len

JSONPatch.__len__()[source]

The number of outstanding patches.

Iterators

__iter__

JSONPatch.__iter__()[source]

Provides an iterator foreseen for large amounts of in-memory patches.

JSONPatchItem

class jsondata.jsonpatch.JSONPatchItem(op, target, param=None, **kargs)[source]

Record entry for list of patch tasks.

Attributes:
op:

operations:

add, copy, move, remove, replace, test
target:
JSONPointer for the modification target, see RFC6902.
value:
Value, either a branch, or a leaf of the JSON data structure.
src:
JSONPointer for the modification source, see RFC6902.

Methods

__init__

JSONPatchItem.__init__(op, target, param=None, **kargs)[source]

Create an entry for the patch list.

Args:
op:

Operation:

add, copy, move, remove, replace, test
target:

Target node.

target := (
    <rfc6901-string>
    | JSONPointer
    | <path-items-list>
    )
param:

Specific parameter for the operation.

type operation
value add, replace, test
src copy, move
param None for ‘remove’
kargs:
replace:

Replace masked characters in target specification.

replace := (
     True    # replaces rfc6901 escape sequences: ~0 and ~1
   | False   # omit unescaping
)

Note

Match operations are proceeded literally, thus the escaped characters should be consistent, see rfc6901, Section 3.

default := False

Returns:
When successful returns ‘True’, else returns either ‘False’, or raises an exception. Success is the complete addition only, thus one failure returns False.
Raises:
JSONDataPatchItemError

__repr__

JSONPatchItem.__repr__()[source]

Prints the patch string in accordance to RFC6901.

__str__

JSONPatchItem.__str__()[source]

Prints the patch string in accordance to RFC6901.

apply

JSONPatchItem.apply(jsondata, **kargs)[source]

Applies the present patch list on the provided JSON document.

Args:
jsondata:
Document to be patched.
kargs:
replace:

Replace masked characters in target specification.

replace := (
     True    # replaces rfc6901 escape sequences: ~0 and ~1
   | False   # omit unescaping
)

Note

Match operations are proceeded literally, thus the escaped characters should be consistent, see rfc6901, Section 3.

If already decoded e.g. by the constructor, than should be FALSE, is not idempotent.

default := False

Returns:

When successful returns ‘True’, else raises an exception. Or returns a tuple:

(n,lerr): 

n:    number of present active entries
lerr: list of failed entries
Raises:
JSONDataPatchError:

repr_export

JSONPatchItem.repr_export()[source]

Prints the patch string for export in accordance to RFC6901.

str_export

JSONPatchItem.str_export()[source]

Pretty prints the patch string for export in accordance to RFC6901.

Operators

‘()’

JSONPatchItem.__call__(jdata)[source]

Evaluates the related task for the provided data.

Args:
jdata:
JSON data the task has to be applied on.
Returns:

Returns a tuple of:

(n,lerr): 

n:    number of present active entries
lerr: list of failed entries
Raises:
JSONDataPatchError:

‘[]’

JSONPatchItem.__getitem__(key)[source]

Support of various mappings.

  1. self[key]
  2. self[i:j:k]
  3. x in self
  4. for x in self

‘S==x’

JSONPatchItem.__eq__(x=None)[source]

Compares this pointer with x.

Args:
x:
A valid Pointer.
Returns:
True or False.
Raises:
JSONPointerError

‘S!=x’

JSONPatchItem.__ne__(x)[source]

Compares this pointer with x.

Args:
x: A valid Pointer.
Returns:
True or False.
Raises:
JSONPointerError

JSONPatchItemRaw

class jsondata.jsonpatch.JSONPatchItemRaw(patchstring, **kargs)[source]

Adds native patch strings or an unsorted dict for RFC6902.

Calls parent JSONPatchItem.

Methods

__init__

JSONPatchItemRaw.__init__(patchstring, **kargs)[source]

Parse a raw patch string in accordance to RFC6902.

Class: JSONPatchFilter

class jsondata.jsonpatch.JSONPatchFilter(**kargs)[source]

Filtering capabilities on the entries of patch lists.

Warning

Not yet implemented.

Methods

__init__

JSONPatchFilter.__init__(**kargs)[source]
Args:
kargs:

Filter parameters:

common:

contain=(True|False): Contain, else equal.

type=<node-type>: Node is of type.

paths:

branch=<branch>:

deep=(): Determines the depth of comparison.

prefix=<prefix>: Any node of prefix. If prefix is
absolute: the only and one, else None. relative: any node prefixed by the path fragment.
values:
val=<node-value>: Node ha the value.
Returns:
True or False
Raises:
JSONPointerError:

Operators

‘==’

JSONPatchFilter.__eq__(x)[source]

‘!=’

JSONPatchFilter.__ne__(x)[source]

Exceptions

exception jsondata.jsonpatch.JSONDataPatchError(*arg)[source]
exception jsondata.jsonpatch.JSONDataPatchItemError(*arg)[source]