Stats

271 Contributors: 7 Tuesday, July 26, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

JSON Module

Remarks

For full documentation including version-specific functionality, please check the official documentation.

Types

Defaults

the json module will handle encoding and decoding of the below types by default:

De-serialisation types:

JSONPython
objectdict
arraylist
stringstr
number (int)int
number (real)float
true, falseTrue, False
nullNone

The json module also understands NaN, Infinity, and -Infinity as their corresponding float values, which is outside the JSON spec.

Serialisation types:

PythonJSON
dictobject
list, tuplearray
strstring
int, float, (int/float)-derived Enumsnumber
Truetrue
Falsefalse
Nonenull

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.

Custom (de-)serialisation

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.

Serialisation:

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)

De-serialisation:

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)

Further custom (de-)serialisation:

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)

Related Examples