def dumps(obj, **kargs): ''' 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 :ref:`encoding` (in short that it has an attribute or property to provide a value for each constructor parameter). :param obj: The Python object (or collection) to encode. :param kargs: Additional parameters are passed directly to the corresponding routine in Python's json package. :return: 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')]}), ... sort_keys=True) '[{"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]})) >>> # use pprints to get consistent dict order >>> pprint(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. ''' return dumps_(obj, cls=JSONEncoder, **kargs)
def test_dumps_decimal(self): config["agent_pretty_json"] = False data = {"decimal": Decimal("1.2")} self.assertEqual( dumps(data), dumps_(data, default=default_json_encoder))
def test_dumps_datetime(self): config["agent_pretty_json"] = False data = {"datetime": datetime.utcnow()} self.assertEqual( dumps(data), dumps_(data, default=default_json_encoder))
def test_dumps_single_argument(self): config["agent_pretty_json"] = False data = self.data.keys()[0] self.assertEqual(dumps(data), dumps_(data))
def test_dumps_not_pretty(self): config["agent_pretty_json"] = False self.assertEqual(dumps(self.data), dumps_(self.data))
def test_dumps_pretty(self): config["agent_pretty_json"] = True self.assertEqual(dumps(self.data), dumps_(self.data, indent=2))
def dumps(*a, **kw): kw['cls'] = LicornEncoder return dumps_(*a, **kw)