For full documentation including version-specific functionality, please check the official documentation.
the json
module will handle encoding and decoding of the below types by default:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true, false | True, False |
null | None |
The json
module also understands NaN
, Infinity
, and -Infinity
as their corresponding float values, which is outside the JSON spec.
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, (int/float)-derived Enums | number |
True | true |
False | false |
None | null |
To disallow encoding of NaN
, Infinity
, and -Infinity
you must encode with allow_nan=False
. This will then raise a ValueError
if you attempt to encode these values.
There are various hooks which allow you to handle data that needs to be represented differently. Use of functools.partial
allows you to partially apply the relevant parameters to these functions for convenience.
You can provide a function that operates on objects before they are serialised like so:
# my_json module
import json
from functools import partial
def serialise_object(obj):
# Do something to produce json-serialisable data
return dict_obj
dump = partial(json.dump, default=serialise_object)
dumps = partial(json.dumps, default=serialise_object)
There are various hooks that are handled by the json functions, such as object_hook and parse_float. For an exhaustive list for your version of python, see here.
# my_json module
import json
from functools import partial
def deserialise_object(dict_obj):
# Do something custom
return obj
def deserialise_float(str_obj):
# Do something custom
return obj
load = partial(json.load, object_hook=deserialise_object, parse_float=deserialise_float)
loads = partial(json.loads, object_hook=deserialise_object, parse_float=deserialise_float)
The json
module also allows for extension/substitution of the json.JSONEncoder
and json.JSONDecoder
to handle miscellaneous types. The hooks documented above can be added as defaults by creating an equivalently named method. To use these simply pass the class as the cls
parameter to the relevant function. Use of functools.partial
allows you to partially apply the cls parameter to these functions for convenience, e.g.
# my_json module
import json
from functools import partial
class MyEncoder(json.JSONEncoder):
# Do something custom
class MyDecoder(json.JSONDecoder):
# Do something custom
dump = partial(json.dump, cls=MyEncoder)
dumps = partial(json.dumps, cls=MyEncoder)
load = partial(json.load, cls=MyDecoder)
loads = partial(json.loads, cls=MyDecoder)