jsonpickle API

Contents

jsonpickle – High Level API

jsonpickle.encode(value, unpicklable=True, max_depth=None)

Return a JSON formatted representation of value, a Python object.

The keyword argument ‘unpicklable’ defaults to True. If set to False, the output will not contain the information necessary to turn the JSON data back into Python objects.

The keyword argument ‘max_depth’ defaults to None. If set to a non-negative integer then jsonpickle will not recurse deeper than ‘max_depth’ steps into the object. Anything deeper than ‘max_depth’ is represented using a Python repr() of the object.

>>> encode('my string')
'"my string"'
>>> encode(36)
'36'
>>> encode({'foo': True})
'{"foo": true}'
>>> encode({'foo': True}, max_depth=0)
'"{\'foo\': True}"'
>>> encode({'foo': True}, max_depth=1)
'{"foo": "True"}'
jsonpickle.decode(string)

Convert a JSON string into a Python object.

>>> str(decode('"my string"'))
'my string'
>>> decode('36')
36

Choosing and Loading Backends

jsonpickle allows the user to specify what JSON backend to use when encoding and decoding. By default, jsonpickle will try to use, in the following order, simplejson, json, and demjson. The prefered backend can be set via jsonpickle.set_preferred_backend(). Additional JSON backends can be used via jsonpickle.load_backend().

For example, users of Django can use the version of simplejson that is bundled in Django:

jsonpickle.load_backend('django.util.simplejson', 'dumps', 'loads', ValueError))
jsonpickle.set_preferred_backend('django.util.simplejson')

Supported backends:

Experimental backends:

jsonpickle.set_preferred_backend(self, name)

Set the preferred json backend.

If a preferred backend is set then jsonpickle tries to use it before any other backend.

For example:

set_preferred_backend('simplejson')

If the backend is not one of the built-in jsonpickle backends (json/simplejson, or demjson) then you must load the backend prior to calling set_preferred_backend.

AssertionError is raised if the backend has not been loaded.

jsonpickle.load_backend(self, name, encode_name, decode_name, decode_exc)

Load a JSON backend by name.

This method loads a backend and sets up references to that backend’s encode/decode functions and exception classes.

Parameters:
  • encode_name – is the name of the backend’s encode method. The method should take an object and return a string.
  • decode_name – names the backend’s method for the reverse operation – returning a Python object from a string.
  • decode_exc – can be either the name of the exception class used to denote decoding errors, or it can be a direct reference to the appropriate exception class itself. If it is a name, then the assumption is that an exception class of that name can be found in the backend module’s namespace.
jsonpickle.remove_backend(self, name)

Remove all entries for a particular backend.

jsonpickle.set_encoder_options(self, name, *args, **kwargs)

Associate encoder-specific options with an encoder.

After calling set_encoder_options, any calls to jsonpickle’s encode method will pass the supplied args and kwargs along to the appropriate backend’s encode method.

For example:

set_encoder_options('simplejson', sort_keys=True, indent=4)
set_encoder_options('demjson', compactly=False)

See the appropriate encoder’s documentation for details about the supported arguments and keyword arguments.

jsonpickle.handlers – Custom Serialization Handlers

The jsonpickle.handlers.registry allows plugging in custom serialization handlers at run-time. This is useful when jsonpickle is unable to serialize objects that are not under your direct control.

class jsonpickle.handlers.BaseHandler(base)

Abstract base class for handlers.

flatten(obj, data)

Flatten obj into a json-friendly form.

Parameters :
  • obj: object of type
restore(obj)

Restores the obj to type

Parameters :
  • object: json-friendly object
class jsonpickle.handlers.Registry
get(cls)

Get the customer handler for obj (if any)

Parameters :
  • cls: class to handle
register(cls, handler)

Register handler.

Parameters :
  • cls: Object class
  • handler: BaseHandler subclass
unregister(cls)

Unregister hander.

Parameters :
  • cls: Object class

Low Level API

Typically this low level functionality is not needed by clients.

jsonpickle.JSONPluginMgr – Management of JSON Backends

class jsonpickle.JSONPluginMgr

The JSONPluginMgr handles encoding and decoding.

It tries these modules in this order:
simplejson, json, demjson

simplejson is a fast and popular backend and is tried first. json comes with python2.6 and is tried second. demjson is the most permissive backend and is tried last.

decode(string)

Attempt to decode an object from a JSON string.

This tries the loaded backends in order and passes along the last exception if no backends are able to decode the string.

encode(obj)

Attempt to encode an object into JSON.

This tries the loaded backends in order and passes along the last exception if no backend is able to encode the object.

load_backend(name, encode_name, decode_name, decode_exc)

Load a JSON backend by name.

This method loads a backend and sets up references to that backend’s encode/decode functions and exception classes.

Parameters:
  • encode_name – is the name of the backend’s encode method. The method should take an object and return a string.
  • decode_name – names the backend’s method for the reverse operation – returning a Python object from a string.
  • decode_exc – can be either the name of the exception class used to denote decoding errors, or it can be a direct reference to the appropriate exception class itself. If it is a name, then the assumption is that an exception class of that name can be found in the backend module’s namespace.
remove_backend(name)

Remove all entries for a particular backend.

set_encoder_options(name, *args, **kwargs)

Associate encoder-specific options with an encoder.

After calling set_encoder_options, any calls to jsonpickle’s encode method will pass the supplied args and kwargs along to the appropriate backend’s encode method.

For example:

set_encoder_options('simplejson', sort_keys=True, indent=4)
set_encoder_options('demjson', compactly=False)

See the appropriate encoder’s documentation for details about the supported arguments and keyword arguments.

set_preferred_backend(name)

Set the preferred json backend.

If a preferred backend is set then jsonpickle tries to use it before any other backend.

For example:

set_preferred_backend('simplejson')

If the backend is not one of the built-in jsonpickle backends (json/simplejson, or demjson) then you must load the backend prior to calling set_preferred_backend.

AssertionError is raised if the backend has not been loaded.

jsonpickle.pickler – Python to JSON

class jsonpickle.pickler.Pickler(unpicklable=True, max_depth=None)

Converts a Python object to a JSON representation.

Setting unpicklable to False removes the ability to regenerate the objects into object types beyond what the standard simplejson library supports.

Setting max_depth to a negative number means there is no limit to the depth jsonpickle should recurse into an object. Setting it to zero or higher places a hard limit on how deep jsonpickle recurses into objects, dictionaries, etc.

>>> p = Pickler()
>>> p.flatten('hello world')
'hello world'
flatten(obj)

Takes an object and returns a JSON-safe representation of it.

Simply returns any of the basic builtin datatypes

>>> p = Pickler()
>>> p.flatten('hello world')
'hello world'
>>> p.flatten(u'hello world')
u'hello world'
>>> p.flatten(49)
49
>>> p.flatten(350.0)
350.0
>>> p.flatten(True)
True
>>> p.flatten(False)
False
>>> r = p.flatten(None)
>>> r is None
True
>>> p.flatten(False)
False
>>> p.flatten([1, 2, 3, 4])
[1, 2, 3, 4]
>>> p.flatten((1,2,))[tags.TUPLE]
[1, 2]
>>> p.flatten({'key': 'value'})
{'key': 'value'}

jsonpickle.unpickler – JSON to Python

class jsonpickle.unpickler.Unpickler
restore(obj)

Restores a flattened object to its original python state.

Simply returns any of the basic builtin types

>>> u = Unpickler()
>>> u.restore('hello world')
'hello world'
>>> u.restore({'key': 'value'})
{'key': 'value'}
jsonpickle.unpickler.has_tag(obj, tag)

Helper class that tests to see if the obj is a dictionary and contains a particular key/tag.

>>> obj = {'test': 1}
>>> has_tag(obj, 'test')
True
>>> has_tag(obj, 'fail')
False
>>> has_tag(42, 'fail')
False
jsonpickle.unpickler.loadclass(module_and_name)

Loads the module and returns the class.

>>> loadclass('samples.Thing')
<class 'samples.Thing'>
>>> loadclass('example.module.does.not.exist.Missing')
>>> loadclass('samples.MissingThing')
jsonpickle.unpickler.loadrepr(reprstr)

Returns an instance of the object from the object’s repr() string. It involves the dynamic specification of code.

>>> from jsonpickle import tags
>>> loadrepr('samples/samples.Thing("json")')
samples.Thing("json")

jsonpickle.util – Helper functions

Helper functions for pickling and unpickling. Most functions assist in determining the type of an object.

jsonpickle.util.is_collection(obj)

Helper method to see if the object is a Python collection (list, set, or tuple). >>> is_collection([4]) True

jsonpickle.util.is_collection_subclass(obj)

Returns True if obj is a subclass of a collection type, such as list set, tuple, etc.. obj must be a subclass and not the actual builtin, such as list, set, tuple, etc..

>>> class Temp(list): pass
>>> is_collection_subclass(Temp())
True
jsonpickle.util.is_dictionary(obj)

Helper method for testing if the object is a dictionary.

>>> is_dictionary({'key':'value'})
True
jsonpickle.util.is_dictionary_subclass(obj)

Returns True if obj is a subclass of the dict type. obj must be a subclass and not the actual builtin dict.

>>> class Temp(dict): pass
>>> is_dictionary_subclass(Temp())
True
jsonpickle.util.is_function(obj)

Returns true if passed a function

>>> is_function(lambda x: 1)
True
>>> is_function(locals)
True
>>> def method(): pass
>>> is_function(method)
True
>>> is_function(1)
False
jsonpickle.util.is_installed(module)

Tests to see if module is available on the sys.path

>>> is_installed('sys')
True
>>> is_installed('hopefullythisisnotarealmodule')
False
jsonpickle.util.is_list(obj)

Helper method to see if the object is a Python list.

>>> is_list([4])
True
jsonpickle.util.is_module(obj)

Returns True if passed a module

>>> import os
>>> is_module(os)
True
jsonpickle.util.is_noncomplex(obj)

Returns True if obj is a special (weird) class, that is more complex than primitive data types, but is not a full object. Including:

jsonpickle.util.is_object(obj)

Returns True is obj is a reference to an object instance.

>>> is_object(1)
True
>>> is_object(object())
True
>>> is_object(lambda x: 1)
False
jsonpickle.util.is_picklable(name, value)

Return True if an object cannot be pickled

>>> import os
>>> is_picklable('os', os)
True
>>> def foo(): pass
>>> is_picklable('foo', foo)
False
jsonpickle.util.is_primitive(obj)

Helper method to see if the object is a basic data type. Strings, integers, longs, floats, booleans, and None are considered primitive and will return True when passed into is_primitive()

>>> is_primitive(3)
True
>>> is_primitive([4,4])
False
jsonpickle.util.is_repr(obj)

Returns True if the obj must be encoded and decoded using the repr() function. Including:

jsonpickle.util.is_set(obj)

Helper method to see if the object is a Python set.

>>> is_set(set())
True
jsonpickle.util.is_tuple(obj)

Helper method to see if the object is a Python tuple.

>>> is_tuple((1,))
True
jsonpickle.util.is_type(obj)

Returns True is obj is a reference to a type.

>>> is_type(1)
False
>>> is_type(object)
True
>>> class Klass: pass
>>> is_type(Klass)
True