Utilities for converting datasets.

fixture.dataset.converter.dataset_to_json(dataset, fp=None, default=<function default_json_converter at 0x1c5bf70>, wrap=None)

Converts a DataSet class or instance to JSON (JavaScript Object Notation).

See Converting a DataSet to JSON for detailed usage.

Keyword Arguments

An optional file-like object (must implement fp.write()). When this is not None, the output is written to the fp object, otherwise the output is returned

A callable that takes one argument (an object) and returns output suitable for JSON serialization. This will only be called if the object cannot be serialized. For example:

>>> def encode_complex(obj):
...     if isinstance(obj, complex):
...         return [obj.real, obj.imag]
...     raise TypeError("%r is not JSON serializable" % (o,))
>>> from fixture import DataSet
>>> class ComplexData(DataSet):
...     class math_stuff:
...         complex = 2 + 1j
>>> dataset_to_json(ComplexData, default=encode_complex)
'[{"complex": [2.0, 1.0]}]'

A callable that takes one argument, the list of dictionaries before they are converted to JSON. For example:

>>> def wrap_in_dict(objects):
...     return {'data': objects}
>>> from fixture import DataSet
>>> class ColorData(DataSet):
...     class red:
...         color = "red"
>>> dataset_to_json(ColorData, wrap=wrap_in_dict)
'{"data": [{"color": "red"}]}'

Returns a JSON encoded string unless you specified the fp keyword

Previous topic


Next topic