jsoner package

jsoner.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=<class 'jsoner.serialization.JsonEncoder'>, indent=None, separators=None, default=None, sort_keys=False, **kw)

Serialize obj to a JSON formatted str.

If skipkeys is true then dict keys that are not basic types (str, int, float, bool, None) will be skipped instead of raising a TypeError.

If ensure_ascii is false, then the return value can contain non-ASCII characters if they appear in strings contained in obj. Otherwise, all such characters are escaped in JSON strings.

If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse).

If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.

If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.

To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

jsoner.loads(s, *, encoding=None, cls=None, object_hook=<function json_hook>, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object.

object_hook is an optional function that will be called with the result of any object literal decode (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.

parse_float, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal).

parse_int, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

parse_constant, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered.

To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used.

The encoding argument is ignored and deprecated.

jsoner.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=<class 'jsoner.serialization.JsonEncoder'>, indent=None, separators=None, default=None, sort_keys=False, **kw)

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object).

If skipkeys is true then dict keys that are not basic types (str, int, float, bool, None) will be skipped instead of raising a TypeError.

If ensure_ascii is false, then the strings written to fp can contain non-ASCII characters if they appear in strings contained in obj. Otherwise, all such characters are escaped in JSON strings.

If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse).

If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.

If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.

To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

jsoner.load(fp, *, cls=None, object_hook=<function json_hook>, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object.

object_hook is an optional function that will be called with the result of any object literal decode (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.

To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used.

Submodules

jsoner.serialization module

class jsoner.serialization.DictConvertible[source]

Bases: abc.ABC

This abstract class implements the to_dict() and from_dict(). Every class implementing those two methods will be a subclass of DictConvertible. It is not necessary to inherit from this class.

class jsoner.serialization.JsonEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

JsonEncoder will decode all objects, which implement either to_dict and from_dict or to_str and from_str.

Note

from_str() and from_dict() must be a classmethod. It is enough to implement either from_str() and to_str() or from_dict() and to_dict(). If both are implemented, then from_dict() and to_dict() are preferred.

If you do not want to implement methods in your class, or you might have no access to the class definition, you can use jsoner.registry.encoders() and jsoner.registry.decoders().

default(obj, *args, **kwargs)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
class jsoner.serialization.JsonerSerializable[source]

Bases: abc.ABC

The JsonerSerializable serves as an abstract class which indicated if an instance can be serialized by Jsoner. Therefore it implements the __subclasshook__() method.

An object is serializable by Jsoner if it is registered in the encoding-, decoding-registry or if it is convertible to a dict or to a string.

class jsoner.serialization.StrConvertible[source]

Bases: abc.ABC

This abstract class implements the to_str() and from_str(). Every class implementing those two methods will be a subclass of StrConvertible. It is not necessary to inherit from this class.

jsoner.serialization.json_hook(primitive: Any) → Any[source]

This hook will try to recreate an object from the data it receives. It it fails to do so, it will just return the original data.

Parameters:primitive
Returns:
jsoner.serialization.maybe_convert_to_obj(data: dict) → Any[source]

This function will try to create an object from the data dictionary.

Parameters:data
Returns:
jsoner.serialization.obj_spec(obj_or_type: Union[object, type]) → str[source]

This function returns the path of the argument class.

If the argument is an instance of type, it returns the path of the argument itself.

Usage::
>>> from jsoner.serialization import obj_spec
>>> class A:
...     pass
>>> obj_spec(A)  # doctest: +ELLIPSIS
'...A'
>>> a = A()
>>> obj_spec(a)  # doctest: +ELLIPSIS
'...A'
Parameters:obj_or_type
Returns:

jsoner.registry module

class jsoner.registry.Registry(**kwargs)[source]

Bases: collections.UserDict

The Registry allows simple key-value mapping. Each key is only allowed once in the registry.

Usage::
>>> from jsoner.registry import Registry
>>> reg = Registry()
>>> reg.add('foo', 42)
>>> reg.get('foo')
42
>>> reg = Registry()
>>> @reg.register('foo')
... def foo():
...     return 42
>>> reg.get('foo')()
42
add(key: Any, value: Any) → None[source]

Adds the key, value pair to the registry. Each key is only allowed once in the registry.

Parameters:
  • key
  • value
Returns:

Raises:

KeyError – If the key is already in the registry.

register(key: Any) → Callable[source]

register() servers as a decorator to add functions to the registry.

Parameters:key
Returns:Callable
registry

returns: The registry dictionary. :rtype: dict

class jsoner.registry.SubclassRegistry(**kwargs)[source]

Bases: jsoner.registry.Registry

The SubclassRegistry will not only map a single key-value pair, but will also retrieve a value if the key, or the type of the key is a Subclass of any of the keys.

If the key, seems to be an object, which could potentially be in the registry but is not found at once, the SubclassRegistry will search the mro of the object and check against its entries.

Usage::
>>> from jsoner.registry import SubclassRegistry
>>> reg = SubclassRegistry()
>>> reg.add(dict, 42)
>>> reg.get(dict)
42
>>> class A:
...     pass
>>> class B(A):
...     pass
>>> reg.add(A, 'bar')
>>> reg.get(B)
'bar'
>>> reg.get(B())
'bar'

The registration also works with strings

>>> from datetime import datetime
>>> reg.add('datetime.datetime', 'foo')
>>> reg.get(datetime)
'foo'
>>> reg.get('dict')
42

Furthermore it can be used as decorator.

>>> reg = SubclassRegistry()
>>> @reg.register(A)
... def foo():
...     return 42
>>> reg.get(A)()
42
>>> reg.get(B)()
42
jsoner.registry.decoders = {}

decoders contains the inverse functions-type mapping for encoders.

jsoner.registry.encoders = {}

encoders contains a mapping of types and encoding functions. An encoding function takes an argument and returns a value which should be json serializable. The function which is defined in decoders must be able to recreate the object from the returned value.

jsoner.registry.import_object(path: str) → Any[source]

Import the object or raise an ImportError if the object is not found.

Parameters:path – The path to the object.
Returns:The imported object.
Raises:ImportError

jsoner.errors module

exception jsoner.errors.JsonEncodingError[source]

Bases: jsoner.errors.JsonerException

This error occurs if Jsoner cannot encode your object to json.

exception jsoner.errors.JsonerException[source]

Bases: Exception

Base Exception class