API Reference
JSON encoder utilising functools.singledispatch to support custom encoders for both Python’s built-in classes and user-created classes, without as much legwork.
Creating and registering a custom encoder is as easy as:
>>> import sdjson
>>>
>>> @sdjson.register_encoder(MyClass)
>>> def encode_myclass(obj):
... return dict(obj)
>>>
In this case, MyClass
can be made JSON-serializable simply by calling
dict
on it. If your class requires more complicated logic
to make it JSON-serializable, do that here.
Then, to dump the object to a string:
>>> class_instance = MyClass()
>>> print(sdjson.dumps(class_instance))
'{"menu": ["egg and bacon", "egg sausage and bacon", "egg and spam", "egg bacon and spam"],
"today\'s special": "Lobster Thermidor au Crevette with a Mornay sauce served in a Provencale
manner with shallots and aubergines garnished with truffle pate, brandy and with a fried egg
on top and spam."}'
>>>
Or to dump to a file:
>>> with open("spam.json", "w") as fp:
... sdjson.dumps(class_instance, fp)
...
>>>
sdjson
also provides access to load()
, loads()
, JSONDecoder
,
JSONDecodeError
, and JSONEncoder
from the json
module,
allowing you to use sdjson
as a drop-in replacement for json
.
If you wish to dump an object without using the custom encoders, you can pass a different
JSONEncoder
subclass, or indeed JSONEncoder
itself to get the stock functionality.
>>> sdjson.dumps(class_instance, cls=sdjson.JSONEncoder)
>>>
When you’ve finished, if you want to unregister the encoder you can run:
>>> sdjson.unregister_encoder(MyClass)
>>>
to remove the encoder for MyClass
. If you want to replace the encoder with a
different one it is not necessary to call this function: the
@sdjson.register_encoder
decorator will replace any existing decorator for the given class.
Classes:
|
Alias of |
|
Alias of |
Functions:
|
Serialize custom Python classes to JSON. |
|
Serialize custom Python classes to JSON. |
|
Alias of |
|
Alias of |
|
Registers a new handler for the given type. |
|
Unregister the handler for the given type. |
-
class
JSONDecoder
(*args, **kwargs)[source] Bases:
JSONDecoder
Alias of
json.JSONDecoder
.Simple JSON <http://json.org> decoder
Performs the following translations in decoding by default:
JSON
Python
object
dict
array
list
string
str
number (int)
int
number (real)
float
true
True
false
False
null
None
It also understands
NaN
,Infinity
, and-Infinity
as their correspondingfloat
values, which is outside the JSON spec.Methods:
decode
(*args, **kwargs)Return the Python representation of
s
(astr
instance containing a JSON document).raw_decode
(*args, **kwargs)Decode a JSON document from
s
(astr
beginning with a JSON document) and return a 2-tuple of the Python representation and the index ins
where the document ended.
-
class
JSONEncoder
(*args, **kwargs)[source] Bases:
JSONEncoder
Alias of
json.JSONEncoder
.Extensible JSON <http://json.org> encoder for Python data structures.
Supports the following objects and types by default:
Python
JSON
dict
object
list, tuple
array
str
string
int, float
number
True
true
False
false
None
null
To extend this to recognize other objects, subclass and implement a
default()
method with another method that returns a serializable object foro
if possible, otherwise it should call the superclass implementation (to raiseTypeError
).Methods:
default
(o)Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).encode
(o)Return a JSON string representation of a Python data structure.
iterencode
(o[, _one_shot])Encode the given object and yield each string representation as available.
-
default
(o)[source] Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).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)
- Return type
-
-
dump
(obj, fp, **kwargs)[source] Serialize custom Python classes to JSON. Custom classes can be registered using the
@encoders.register(<type>)
decorator.Serialize
obj
as a JSON formatted stream tofp
(a.write()
-supporting file-like object).If
skipkeys
is true thendict
keys that are not basic types (str
,int
,float
,bool
,None
) will be skipped instead of raising aTypeError
.If
ensure_ascii
is false, then the strings written tofp
can contain non-ASCII characters if they appear in strings contained inobj
. 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 anRecursionError
(or worse).If
allow_nan
is false, then it will be aValueError
to serialize out of rangefloat
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 isNone
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 thedefault()
method to serialize additional types), specify it with thecls
kwarg; otherwiseJSONEncoder
is used.
-
dumps
(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kwargs)[source] Serialize custom Python classes to JSON. Custom classes can be registered using the
@encoders.register(<type>)
decorator.Serialize
obj
to a JSON formattedstr
.If
skipkeys
is true thendict
keys that are not basic types (str
,int
,float
,bool
,None
) will be skipped instead of raising aTypeError
.If
ensure_ascii
is false, then the return value can contain non-ASCII characters if they appear in strings contained inobj
. 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 anRecursionError
(or worse).If
allow_nan
is false, then it will be aValueError
to serialize out of rangefloat
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 isNone
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 thedefault()
method to serialize additional types), specify it with thecls
kwarg; otherwiseJSONEncoder
is used.- Return type
-
load
(*args, **kwargs)[source] Alias of
json.load()
.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 (adict
). The return value ofobject_hook
will be used instead of thedict
. 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 ofobject_pairs_hook
will be used instead of thedict
. This feature can be used to implement custom decoders. Ifobject_hook
is also defined, theobject_pairs_hook
takes priority.To use a custom
JSONDecoder
subclass, specify it with thecls
kwarg; otherwiseJSONDecoder
is used.
-
loads
(*args, **kwargs)[source] Alias of
json.loads()
.Deserialize
s
(astr
,bytes
orbytearray
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 (adict
). The return value ofobject_hook
will be used instead of thedict
. 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 ofobject_pairs_hook
will be used instead of thedict
. This feature can be used to implement custom decoders. Ifobject_hook
is also defined, theobject_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 thecls
kwarg; otherwiseJSONDecoder
is used.
-
register_encoder
(cls, func=None) Registers a new handler for the given type.
Can be used as a decorator or a regular function:
@register_encoder(bytes) def bytes_encoder(obj): return obj.decode("UTF-8") def int_encoder(obj): return int(obj) register_encoder(int, int_encoder)