Contents
Return a JSON formatted representation of value, a Python object.
Parameters: |
|
---|
>>> 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"}'
Convert a JSON string into a Python object.
The keyword argument ‘keys’ defaults to False. If set to True then jsonpickle will decode non-string dictionary keys into python objects via the jsonpickle protocol.
>>> str(decode('"my string"'))
'my string'
>>> decode('36')
36
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:
- json in Python 2.6+
- simplejson
- demjson
Experimental backends:
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.
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: |
|
---|
Remove all entries for a particular backend.
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 supports the standard pickle __getstate__ and __setstate__ protocol for representating object instances.
Classes can further influence how their instances are pickled; if the class defines the method __getstate__(), it is called and the return state is pickled as the contents for the instance, instead of the contents of the instance’s dictionary. If there is no __getstate__() method, the instance’s __dict__ is pickled.
Upon unpickling, if the class also defines the method __setstate__(), it is called with the unpickled state. If there is no __setstate__() method, the pickled state must be a dictionary and its items are assigned to the new instance’s dictionary. If a class defines both __getstate__() and __setstate__(), the state object needn’t be a dictionary and these methods can do what they want.
The jsonpickle.handlers module allows plugging in custom serialization handlers at run-time. This feature is useful when jsonpickle is unable to serialize objects that are not under your direct control.
Custom handlers may be created to handle other objects. Each custom handler must derive from jsonpickle.handlers.BaseHandler and implement flatten and restore.
A handler can be bound to other types by calling jsonpickle.handlers.register().
jsonpickle.customhandlers.SimpleReduceHandler is suitable for handling objects that implement the reduce protocol:
from jsonpickle import handlers
class MyCustomObject(handlers.BaseHandler):
...
def __reduce__(self):
return MyCustomObject, self._get_args()
handlers.register(MyCustomObject, handlers.SimpleReduceHandler)
Flatten obj into a json-friendly form and write result in data
Register this handler for the given class. Suitable as a decorator, e.g.:
@SimpleReduceHandler.handles
class MyCustomClass:
def __reduce__(self):
...
Restore the json-friendly obj to the registered type
Serialization proxy for collections.defaultdict’s default_factory
Custom handler for datetime objects
Datetime objects use __reduce__, and they generate binary strings encoding the payload. This handler encodes that payload to reconstruct the object.
Serialize OrderedDict on Python 3.4+
Python 3.4+ returns multiple entries in an OrderedDict’s reduced form. Previous versions return a two-item tuple. OrderedDictReduceHandler makes the formats compatible.
Opaquely serializes Queue objects
Queues contains mutex and condition variables which cannot be serialized. Construct a new Queue instance when restoring.
Flatten _sre.SRE_Pattern (compiled regex) objects
Typically this low level functionality is not needed by clients.
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(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'}
Resets the object’s internal state.
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'}
Return arguments suitable for __new__()
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
Loads the module and returns the class.
>>> cls = loadclass('datetime.datetime')
>>> cls.__name__
'datetime'
>>> loadclass('does.not.exist')
>>> loadclass('__builtin__.int')()
0
Returns an instance of the object from the object’s repr() string. It involves the dynamic specification of code.
>>> obj = loadrepr('datetime/datetime.datetime.now()')
>>> obj.__class__.__name__
'datetime'
Implement the mandated strategy for dealing with classic classes which cannot be instantiated without __getinitargs__ because they take parameters
Manages encoding and decoding using various backends.
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.
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.
Disable jsonpickle’s fallthrough-on-error behavior
By default, jsonpickle tries the next backend when decoding or encoding using a backend fails.
This can make it difficult to force jsonpickle to use a specific backend, and catch errors, because the error will be suppressed and may not be raised by the subsequent backend.
Calling enable_backend(False) will make jsonpickle immediately re-raise any exceptions raised by the backends.
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 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: |
|
---|
Remove all entries for a particular backend.
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 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.
Helper functions for pickling and unpickling. Most functions assist in determining the type of an object.
Tests if __reduce__ or __reduce_ex__ exists in the object dict or in the class dicts of every class in the MRO except object.
Returns a tuple of booleans (has_reduce, has_reduce_ex)
>>> class Example(object):
... pass
>>> ex = Example()
>>> importable_name(ex.__class__)
'jsonpickle.util.Example'
>>> importable_name(type(25))
'__builtin__.int'
>>> importable_name(None.__class__)
'__builtin__.NoneType'
>>> importable_name(False.__class__)
'__builtin__.bool'
>>> importable_name(AttributeError)
'__builtin__.AttributeError'
Returns true if key exists in obj.__dict__; false if not in. If obj.__dict__ is absent, return default
Returns true if key exists in obj.__slots__; false if not in. If obj.__slots__ is absent, return default
Helper method for testing if the object is a dictionary.
>>> is_dictionary({'key':'value'})
True
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
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
Tests to see if module is available on the sys.path
>>> is_installed('sys')
True
>>> is_installed('hopefullythisisnotarealmodule')
False
Helper method to see if the object is a Python list.
>>> is_list([4])
True
Returns True if passed a module
>>> import os
>>> is_module(os)
True
Return True if obj is a module-global function
>>> import os
>>> is_module_function(os.path.exists)
True
>>> is_module_function(lambda: None)
False
Returns True if obj is a special (weird) class, that is more complex than primitive data types, but is not a full object. Including:
- struct_time
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
Return True if an object can be pickled
>>> import os
>>> is_picklable('os', os)
True
>>> def foo(): pass
>>> is_picklable('foo', foo)
True
>>> is_picklable('foo', lambda: None)
False
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
Returns false if of a type which have special casing, and should not have their __reduce__ methods used
Helper method to see if the object is a sequence (list, set, or tuple).
>>> is_sequence([4])
True
Returns True if obj is a subclass of list, set or tuple.
obj must be a subclass and not the actual builtin, such as list, set, tuple, etc..
>>> class Temp(list): pass
>>> is_sequence_subclass(Temp())
True
Helper method to see if the object is a Python set.
>>> is_set(set())
True
Helper method to see if the object is a Python tuple.
>>> is_tuple((1,))
True
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
Rename builtin modules to a consistent (Python2) module name
This is used so that references to Python’s builtins module can be loaded in both Python 2 and 3. We remap to the “__builtin__” name and unmap it when importing.
See untranslate_module_name() for the reverse operation.
Rename module names mention in JSON to names that we can import
This reverses the translation applied by translate_module_name() to a module name available to the current version of Python.