JSON Serialisation (pytyp.s11n.json)

This module extends the standard Python json library so that it can write and return instances of Python classes. This simplifies Python code that interacts with JSON (you don’t need to use dicts where you would normally use a class, which means you can access values using attributes rather named indices).

Encoding

Tip

For background details see Encoding Support and Type Specifications (pytyp.spec.abcs).

pytyp.s11n.json.dumps(obj, **kargs)[source]

Serialize obj to a JSON formatted string.

This is intended as a direct substitute for the dumps() function in Python’s json package. It supports the same options, except for cls (which is used internally to provide Pytyp’s own encoding).

Unlike the standard Python library, this will also encode Python classes as long as they follow the conventions described in Encoding Support (in short that it has an attribute or property to provide a value for each constructor parameter).

Parameters:
  • obj – The Python object (or collection) to encode.
  • kargs – Additional parameters are passed directly to the corresponding routine in Python’s json package.
Returns:

A string containing the JSON encoded obj.

Here is an example of encoding a Python class, and then reading that back from JSON:

>>> class Example():
...     def __init__(self, foo):
...         self.foo = foo
...     def __repr__(self):
...         return '<Example({0})>'.format(self.foo)
>>> dumps(Example('abc'))
'{"foo": "abc"}'
>>> loads = make_loads(Example)
>>> loads('{"foo": "abc"}')
<Example(abc)>

Lists, tuples and dicts of objects are also handled correctly:

>>> dumps((Example('tuple'), {'a': Example('dict'), 'b': [Example('list')]}))
'[{"foo": "tuple"}, {"a": {"foo": "dict"}, "b": [{"foo": "list"}]}]'

and this can be read back to Python classes, if the correct type specification is given to make_loads():

>>> loads = make_loads((Example, {'a': Example, 'b': [Example]}))
>>> loads('[{"foo": "tuple"}, {"a": {"foo": "dict"}, "b": [{"foo": "list"}]}]')
(<Example(tuple)>, {'a': <Example(dict)>, 'b': [<Example(list)>]})

Even nested classes can be written and read back correctly - see the example for make_loads() below.

pytyp.s11n.json.dump(obj, fp, **kargs)[source]

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

This is intended as a direct substitute for the dump() function in Python’s json package. It supports the same options, except for cls (which is used internally to provide Pytyp’s own encoding).

Unlike the standard Python library, this will also encode Python classes as long as they follow the conventions described in Encoding Support (in short that it has an attribute or property to provide a value for each constructor parameter).

Parameters:
  • obj – The Python object (or collection) to encode.
  • fp – The destination for the data.
  • kargs – Additional parameters are passed directly to the corresponding routine in Python’s json package.
Returns:

None (output written to fp)

class pytyp.s11n.json.JSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Decoding

Tip

For background details see Decoding Support and Type Specifications (pytyp.spec.abcs).

pytyp.s11n.json.make_loads(spec)[source]

Create a replacement for the loads() function in Python’s json package that will deserialize a string containing a JSON document to a Python object.

Parameters:spec – The type specification for the root object. Nested objects are defined by type annotations. See Decoding Support for full details.
Returns:A replacement for loads() in the Python json package, which will read from a string are return the data structured as spec.

For example:

>>> class Example():
...     def __init__(self, foo):
...         self.foo = foo
...     def __repr__(self):
...         return '<Example({0})>'.format(self.foo)
>>> class Container():
...     def __init__(self, *examples:[Example]):
...         self.examples = examples
...     def __repr__(self):
...         return '<Container({0})>'.format(','.join(map(repr, self.examples)))
>>> loads = make_loads(Container)
>>> loads('[{"foo":"abc"}, {"foo":"xyz"}]')
<Container(<Example(abc)>,<Example(xyz)>)>

(note that here, because Container uses *args, it is represented as a list, not a dict).

pytyp.s11n.json.make_load(spec)[source]

Create a replacement for the load() function in Python’s json package that will deserialize a .read()-supporting file-like object containing a JSON document to a Python object.

Parameters:spec – The type specification for the root object. Nested objects are defined by type annotations. See Decoding Support for full details.
Returns:A replacement for load() in the Python json package, which will read from a file are return the data structured as spec.
pytyp.s11n.json.make_JSONDecoder(spec)[source]

Create a custom decoder for the Python json module.

Parameters:spec – The type specification for the root object. Nested objects are defined by type annotations. See Decoding Support for full details.
Returns:A replacement for the JSONDecoder class in the Python json package, which returns data structured as spec.

Table Of Contents

Previous topic

Serialisation Support (pytyp.s11n.base)

Next topic

YAML Serialisation (pytyp.s11n.yaml)

This Page