Package jsondata :: Module JSONPointer :: Class JSONPointer
[hide private]
[frames] | no frames]

Class JSONPointer

source code


Represents exactly one JSONPointer in compliance with IETF RFC6901.
This pointer could be processed by extension, reduction, and general modification
with support of provided methods and path arithmetic operators. 

The JSONPointer is provided at the API as a utf(-8) string in accordance 
to RFC6901, including RFC3869.

For enhancement of the processing performance by the underlying packages 
'json' and 'jsonschema', the pointer is stored and applied in two variants. 

* self.raw: Raw input of the pointer string for the logical API.

* self.ptr: Split elements of the pointer path within a list of keys,
    for the programming interface.
  
The attribute 'self.ptr' contains the path elements in a 
'list'::
   
   ptrlist := (<EMPTY>|plist)
   <EMPTY> := "empty list, represents the whole document"
   plist := pkey [, plist ]
   pkey := (''|int|keyname)
   '' := "the empty string is a valid key too"
   int := "integer index of an array item, just digits"
   keyname := "the valid name of an object/property entry" 

The JSONPointer::

  "/address/0/streetName"

is represented as::

  ['address', 0, 'streetName' ]


The methods and operators are handling the pointer itself, the values
referenced by the pointer are not modified. 

The methods of this class support for multiple input format of 
the JSONPointer. The parameter 'x' in the operations is defined as a
valid JSONPointer fragment. A pointer fragment is a part of a pointer,
which could be the complete pointer itself - the all-fragment. 

The syntax element could be one of::
    
    'str': A string i accordance to RFC6901. Strings are represented 
        internally as unicode utf-8.
        
        Here either the input parameter 'x' is split into
        a list, or in case of combining operations, the self.ptr
        attribute is 'joined' to be used for the method. 

    'int': A numeric value in case of an array index. This value 
        is internally handled for the string representation as a
        unicode utf-8, whereas for the addressing of memory 
        objects the numeric integer value is stored and applied.

    'JSONPointer': The attributes of the input object are used 
        with it's peers.
    
    'list': Expects a path list containing:
        - JSON object names
            Names of the json objects.
        - array indexes
            Numeric index for arrays.
        - JSONPointer
            A JSONPointer object, the path is resolved as a section 
            of overall path.

        The self.ptr attribute is applied for operations.

The node reference is cached by the 'get_node' and 'get_node_or_value' 
method, thus could be accessed by 'self.node', but is not monitored
to be valid. Another call of the method reloads the cache by evaluating
the pointer value on the document again.

The provided value is internally stored as a raw input value, and a list
of keys and indexes for access to in-memory data as provided by the
packages 'json' and 'jsonschema'. Requests for the string representation
are transformed into a pointer path in accordance to RFC6901. This provides
for fast access in case of pointer arithmetics, while providing standards
conform path strings at the interface.

Instance Methods [hide private]
new empty list
__init__(self, ptr, replace=True, **kargs)
Converts and stores a JSONPointer as a list.
source code
 
__add__(self, x)
Appends a Pointer to self.
source code
 
__call__(self, x)
Evaluates the pointed value from the document.
source code
 
__eq__(self, x)
Compares this pointer with x.
source code
 
__ge__(self, x)
Checks containment(>=) of another pointer within this.
source code
 
__gt__(self, x)
Checks containment(>) of another pointer or object within this.
source code
 
__iadd__(self, x)
Add in place x to self, appends a path.
source code
 
__le__(self, x)
Checks containment(<=) of this pointer within another.
source code
 
__lt__(self, x)
Checks containment(<) of this pointer within another.
source code
 
__ne__(self, x)
Compares this pointer with x.
source code
 
__radd__(self, x)
Adds itself as the right-side-argument to the left.
source code
 
__repr__(self)
Returns the attribute self.raw, which is the raw input JSONPointer.
source code
 
__str__(self)
Returns the string for the processed path.
source code
 
check_node_or_value(self, jsondata, parent=False)
Checks the existance of the corresponding node within the JSON document.
source code
 
copy_path_list(self, parent=False)
Returns a deep copy of the objects pointer path list.
source code
 
get_node(self, jsondata, parent=False)
Gets the corresponding node reference for a JSON container type.
source code
 
get_node_and_child(self, jsondata)
Returns a tuple containing the parent node and the child.
source code
 
get_node_or_value(self, jsondata, valtype=None, parent=False)
Gets the corresponding node reference or the JSON value of a leaf.
source code
 
get_node_exist(self, jsondata, parent=False)
Returns the node for valid part of the pointer, and the remaining part.
source code
 
get_path_list(self)
Gets for the corresponding path list of the object pointer for in-memory access on the data of the 'json' package.
source code
 
get_path_list_and_key(self)
Gets for the corresponding path list of the object pointer for in-memory access on the data of the 'json' package.
source code
 
get_pointer(self, forcenotation=None, parent=False)
Gets the objects pointer in compliance to RFC6901.
source code
 
get_raw(self)
Gets the objects raw 6901-pointer.
source code
 
iter_path(self, jsondata=None, parent=False, rev=False)
Iterator for the elements of the path pointer itself.
source code
 
iter_path_nodes(self, jsondata, parent=False, rev=False)
Iterator for the elements the path pointer points to.
source code

Inherited from list: __contains__, __delitem__, __delslice__, __getattribute__, __getitem__, __getslice__, __imul__, __iter__, __len__, __mul__, __new__, __reversed__, __rmul__, __setitem__, __setslice__, __sizeof__, append, count, extend, index, insert, pop, remove, reverse, sort

Inherited from object: __delattr__, __format__, __reduce__, __reduce_ex__, __setattr__, __subclasshook__

Class Variables [hide private]
  VALID_INDEX = re.compile(r'0|[1-9][0-9]*$')
Regular expression for valid numerical index.

Inherited from list: __hash__

Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__init__(self, ptr, replace=True, **kargs)
(Constructor)

source code 
Converts and stores a JSONPointer as a list.

Processes the ABNF of a JSON Pointer from RFC6901.

Args:
    ptr: A JSONPointer to be represented by this object. The
        supported formats are:
            'str': A string i accordance to RFC6901
            JSONPointer: A valid object, will be copied 
                into this, see 'deep'.
            'list': expects a path list, where each item
                is processed for escape and unquote.
    replace: Replaces masked characters.
    **kargs:
        deep: Applies for copy operations on structured data
            'deep' when 'True', else 'swallow' only, which is 
            just a link to the data structure. Flat data types
            are copied by value in any case.
        node: Force to set the pointed node in the internal cache. 
        debug: Enable debugging.

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:
    JSONPointerException:

Returns: new empty list
Overrides: object.__init__

__add__(self, x)
(Addition operator)

source code 
Appends a Pointer to self.

Args:
    x: A valid JSONPointer fragment.

Returns:
    A new object of JSONPointer
    
Raises:
    JSONPointerException:

Overrides: list.__add__

__call__(self, x)
(Call operator)

source code 
Evaluates the pointed value from the document.

Args:
    x: A valid JSON document.

Returns:
    The pointed value, or None.

Raises:
    JSONPointerException

__eq__(self, x)
(Equality operator)

source code 
Compares this pointer with x.

Args:
    x: A valid Pointer.

Returns:
    True or False

Raises:
    JSONPointerException

Overrides: list.__eq__

__ge__(self, x)
(Greater-than-or-equals operator)

source code 
Checks containment(>=) of another pointer within this.

The weight of contained entries is the criteria, though
the shorter is the bigger. This is true only in case of
a containment relation.
 
The number of equal path pointer items is compared.

Args:
    x: A valid Pointer.

Returns:
    True or False

Raises:
    JSONPointerException:

Overrides: list.__ge__

__gt__(self, x)
(Greater-than operator)

source code 
Checks containment(>) of another pointer or object within this.

The number of equal items is compared.

Args:
    x: A valid Pointer.

Returns:
    True or False

Raises:
    JSONPointerException:

Overrides: list.__gt__

__iadd__(self, x)

source code 
Add in place x to self, appends a path.

Args:
    x: A valid Pointer.

Returns:
    'self' with updated pointer attributes

Raises:
    JSONPointerException:

Overrides: list.__iadd__

__le__(self, x)
(Less-than-or-equals operator)

source code 
Checks containment(<=) of this pointer within another.

The number of equal items is compared.

Args:
    x: A valid Pointer.

Returns:
    True or False

Raises:
    JSONPointerException:

Overrides: list.__le__

__lt__(self, x)
(Less-than operator)

source code 
Checks containment(<) of this pointer within another.

The number of equal items is compared.

Args:
    x: A valid Pointer.

Returns:
    True or False

Raises:
    JSONPointerException:

Overrides: list.__lt__

__ne__(self, x)

source code 
Compares this pointer with x.

Args:
    x: A valid Pointer.

Returns:
    True or False

Raises:
    JSONPointerException

Overrides: list.__ne__

__radd__(self, x)
(Right-side addition operator)

source code 
Adds itself as the right-side-argument to the left.

This method appends 'self' to a path fragment on the left.
Therefore it adds the path separator on it's left side only.
The left side path fragment has to maintain to be in 
accordance to RFC6901 by itself.

Once 'self' is added to the left side, it terminates it's
life cycle. Thus another simultaneous add operation is 
handled by the resulting other element.
 
Args:
    x: A valid Pointer.

Returns:
    The updated input of type 'x' as 'x+S(x)'

Raises:
    JSONPointerException:

__repr__(self)
(Representation operator)

source code 

Returns the attribute self.raw, which is the raw input JSONPointer.

Overrides: object.__repr__

__str__(self)
(Informal representation operator)

source code 

Returns the string for the processed path.

Overrides: object.__str__

check_node_or_value(self, jsondata, parent=False)

source code 
Checks the existance of the corresponding node within the JSON document.

Args:
    jsondata: A valid JSON data node.
    parent: Return the parent node of the pointed value.

Returns:
    True or False
    
Raises:
    JSONPointerException:
    forwarded from json

copy_path_list(self, parent=False)

source code 
Returns a deep copy of the objects pointer path list.

Args:
    parent: The parent node of the pointer path.

Returns:
    A copy of the path list.
    
Raises:
    none

get_node(self, jsondata, parent=False)

source code 
Gets the corresponding node reference for a JSON container type.

This method gets nodes of container types. Container 
types of JSON are 'array' a.k.a. in Python 'list', 
and 'objects' a.k.a. in Python 'dict'.

Due to the special case of RFC6902 'append' by the array 
index '-' in combination of the add rules a special 
exception-treatment is required, for details refer to RFC6902.

The 'get_node' method therefore returns only an existing 
node of a of valid non-ambiguous path pointer. This 
excludes pointers containing the symbolic index '-' for 
an array component.

See also related methods:

    get_node_and_child: For Python access to a child node 
        within a container by the container itself, and the
        item key.
    get_node_exist: For the application of partial valid 
        pointer paths of new branches.
    get_node_or_value: For any type of pointed item, either 
        a node, or a value. 

Args:
    jsondata: A valid JSON data node.
    parent: Return the parent node of the pointed value.
        When parent is selected, the pointed child node
        is not verified. 

Returns:
    The node reference.
    
Raises:
    JSONPointerException:
    forwarded from json

get_node_and_child(self, jsondata)

source code 
Returns a tuple containing the parent node and the child.

Args:
    jsondata: A valid JSON data node.

Returns:
    The the tuple:
    (n,c):  n: Node reference to parent container.
            c: Key for the child entry, either an 
               index 'int', or a key ('str', 'unicode'). 
Raises:
    JSONPointerException:
    forwarded from json

get_node_or_value(self, jsondata, valtype=None, parent=False)

source code 
Gets the corresponding node reference or the JSON value of a leaf.

Relies on the standard package 'json' by 'Bob Ippolito <bob@redivi.com>'.
This package supports in the current version the following types:

    +---------------+-------------------+
    | JSON          | Python            |
    +===============+===================+
    | object        | dict              |
    +---------------+-------------------+
    | array         | list              |
    +---------------+-------------------+
    | string        | unicode           |
    +---------------+-------------------+
    | number (int)  | int, long         |
    +---------------+-------------------+
    | number (real) | float             |
    +---------------+-------------------+
    | true          | True              |
    +---------------+-------------------+
    | false         | False             |
    +---------------+-------------------+
    | null          | None              |
    +---------------+-------------------+

    It also understands ``NaN``, ``Infinity``, and
    ``-Infinity`` as their corresponding ``float`` 
    values, which is outside the JSON spec.


The supported standard value types for Python 
of get_node_or_value() are mapped automatically 
as depicted in the following table. Additional
bindings may be implemented by sub-classing.

    +------------------------+-------------------+
    | JSONPointer(jsondata)  | Python-valtype    |
    +========================+===================+
    | object (dict)          | dict              |
    +------------------------+-------------------+
    | array  (list)          | list              |
    +------------------------+-------------------+
    | array  (tuple)         | list              |
    +------------------------+-------------------+
    | string                 | unicode           |
    +------------------------+-------------------+
    | number (int)           | int               |
    +------------------------+-------------------+
    | number (long)          | long              |
    +------------------------+-------------------+
    | number (float)         | float             |
    +------------------------+-------------------+
    | *number (double)       | float             |
    +------------------------+-------------------+
    | number (octal)         | int               |
    +------------------------+-------------------+
    | number (hex)           | int               |
    +------------------------+-------------------+
    | number (binary)        | int               |
    +------------------------+-------------------+
    | number (complex)       | - (custom)        |
    +------------------------+-------------------+
    | true                   | True              |
    +------------------------+-------------------+
    | false                  | False             |
    +------------------------+-------------------+
    | null                   | None              |
    +------------------------+-------------------+

The mappings in detail are:

* object(dict) => dict:
    {a:b} - native Python dictionary

* array(list) => list:
    [a,b] - native Python list

* (*)array(tuple) => list:
    (a,b) - native Python list

* string(str) => unicode"
    "abc" - native Python unicode string UTF-8

* number(int) => int:
    1234, −24, 0 - Integers (unlimited precision)

* number(long) => int:
    1234, −24, 0 - Integers (unlimited precision)

* number(float) => float:
    1.23, 3.14e-10, 4E210, 4.0e+210, 1., .1 - 
    Floating-point (normally implemented as C doubles in CPython)

* (*)number(double) => float:
    1.23, 3.14e-10, 4E210, 4.0e+210, 1., .1 - 
    Floating-point (normally implemented as C doubles in CPython)

* number(octal) => int:
    0o177 - 
    Octal, hex, and binary literals for integers2

* number(hex) => int:
    0x9ff - Octal, hex, and binary literals for integers2

* number(binary) => int:
    0b1111 - Octal, hex, and binary literals for integers2

* number(complex) => <not-supported>(requires custom):
    3+4j, 3.0+4.0j, 3J - Complex numbers

* true(True) => boolean(True):
    True - native Python boolean

* false(False) => boolean(False):
    False - native Python boolean

* null(None) => NoneType(None):
    False - native Python NoneType

Args:
    jsondata: A valid JSON data node.
    valtype: Type of requested value.
    parent: Return the parent node of the pointed value.

Returns:
    The node reference.
    
Raises:
    JSONPointerException:
    forwarded from json

get_node_exist(self, jsondata, parent=False)

source code 
Returns the node for valid part of the pointer, and the remaining part.

This method works similar to the 'get_node' method, whereas it
handles partial valid path pointers, which may also include 
a '-' in accordance to RFC6902.

Therefore the non-ambiguous part of the pointer is resolved, 
and returned with the remaining part for a newly create.
Thus this method is in particular foreseen to support the 
creation of new sub data structures.

The 'get_node' method therefore returns a list of two elements,
the first is the node reference, the second the list of the 
remaining path pointer components. The latter may be empty in
case of a fully valid pointer.


Args:
    jsondata: A valid JSON data node.
    parent: Return the parent node of the pointed value.

Returns:
    The node reference, and the remaining part.
    ret:=[ node, [<remaining-path-components-list>] ]
    
Raises:
    JSONPointerException:
    forwarded from json

get_path_list(self)

source code 
Gets for the corresponding path list of the object pointer for in-memory access on the data of the 'json' package.

Args:
    none

Returns:
    The path list.
    
Raises:
    none

get_path_list_and_key(self)

source code 
Gets for the corresponding path list of the object pointer for in-memory access on the data of the 'json' package.

Args:
    none

Returns:
    The path list.
    
Raises:
    none

get_pointer(self, forcenotation=None, parent=False)

source code 
Gets the objects pointer in compliance to RFC6901.

Args:
    forcenotation: Force the output notation to:
        None := NOTATION_JSON,
        NOTATION_JSON = 0,
        NOTATION_HTTP_FRAGMENT = 1
        
    parent: Get parent of selected node.

Returns:
    The pointer in accordance to RFC6901.
    
Raises:
    none

get_raw(self)

source code 
Gets the objects raw 6901-pointer.

Args:
    none

Returns:
    The raw path.
    
Raises:
    none

iter_path(self, jsondata=None, parent=False, rev=False)

source code 
Iterator for the elements of the path pointer itself.

Args:
    jsondata: If provided a valid JSON data node, the
        path components are successively verified on
        the provided document. If None the path pointer
        components are just iterated.
    parent: Uses the path pointer to parent node.
    rev: Reverse the order, start with last.

Returns:
    Yields the iterator for the current path pointer
    component.
    
Raises:
    JSONPointerException:
    forwarded from json

iter_path_nodes(self, jsondata, parent=False, rev=False)

source code 
Iterator for the elements the path pointer points to.

Args:
    jsondata: A valid JSON data node.
    parent: Uses the path pointer to parent node.
    rev: Reverse the order, start with last.

Returns:
    Yields the iterator of the current node reference.
    
Raises:
    JSONPointerException:
    forwarded from json