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:
JSONDecoderAlias 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-Infinityas their correspondingfloatvalues, which is outside the JSON spec.Methods:
decode(*args, **kwargs)Return the Python representation of
s(astrinstance containing a JSON document).raw_decode(*args, **kwargs)Decode a JSON document from
s(astrbeginning with a JSON document) and return a 2-tuple of the Python representation and the index inswhere the document ended.
-
class
JSONEncoder(*args, **kwargs)[source]¶ Bases:
JSONEncoderAlias 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 foroif 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
objas a JSON formatted stream tofp(a.write()-supporting file-like object).If
skipkeysis true thendictkeys that are not basic types (str,int,float,bool,None) will be skipped instead of raising aTypeError.If
ensure_asciiis false, then the strings written tofpcan contain non-ASCII characters if they appear in strings contained inobj. Otherwise, all such characters are escaped in JSON strings.If
check_circularis false, then the circular reference check for container types will be skipped and a circular reference will result in anRecursionError(or worse).If
allow_nanis false, then it will be aValueErrorto serialize out of rangefloatvalues (nan,inf,-inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN,Infinity,-Infinity).If
indentis 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.Noneis the most compact representation.If specified,
separatorsshould be an(item_separator, key_separator)tuple. The default is(', ', ': ')if indent isNoneand(',', ': ')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
JSONEncodersubclass (e.g. one that overrides thedefault()method to serialize additional types), specify it with theclskwarg; otherwiseJSONEncoderis 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
objto a JSON formattedstr.If
skipkeysis true thendictkeys that are not basic types (str,int,float,bool,None) will be skipped instead of raising aTypeError.If
ensure_asciiis 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_circularis false, then the circular reference check for container types will be skipped and a circular reference will result in anRecursionError(or worse).If
allow_nanis false, then it will be aValueErrorto serialize out of rangefloatvalues (nan,inf,-inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN,Infinity,-Infinity).If
indentis 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.Noneis the most compact representation.If specified,
separatorsshould be an(item_separator, key_separator)tuple. The default is(', ', ': ')if indent isNoneand(',', ': ')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
JSONEncodersubclass (e.g. one that overrides thedefault()method to serialize additional types), specify it with theclskwarg; otherwiseJSONEncoderis 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_hookis an optional function that will be called with the result of any object literal decode (adict). The return value ofobject_hookwill be used instead of thedict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).object_pairs_hookis 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_hookwill be used instead of thedict. This feature can be used to implement custom decoders. Ifobject_hookis also defined, theobject_pairs_hooktakes priority.To use a custom
JSONDecodersubclass, specify it with theclskwarg; otherwiseJSONDecoderis used.
-
loads(*args, **kwargs)[source]¶ Alias of
json.loads().Deserialize
s(astr,bytesorbytearrayinstance containing a JSON document) to a Python object.object_hookis an optional function that will be called with the result of any object literal decode (adict). The return value ofobject_hookwill be used instead of thedict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).object_pairs_hookis 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_hookwill be used instead of thedict. This feature can be used to implement custom decoders. Ifobject_hookis also defined, theobject_pairs_hooktakes 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
JSONDecodersubclass, specify it with theclskwarg; otherwiseJSONDecoderis 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)