### Install jsonpickle from source Source: https://jsonpickle.github.io/_sources/index.rst.txt Install jsonpickle by downloading or checking out the latest code and running the setup script. This method is useful for development or when PyPI is not accessible. ```bash python setup.py install ``` -------------------------------- ### Install jsonpickle using pip Source: https://jsonpickle.github.io/_sources/index.rst.txt Install the jsonpickle library using pip, the Python package installer. This is the recommended method for obtaining the latest version. ```bash pip install -U jsonpickle ``` -------------------------------- ### Check if a module is installed Source: https://jsonpickle.github.io/api.html Tests if a given module name is available on the system's sys.path. This is useful for checking dependencies before attempting to import. ```python is_installed('sys') # Expected output: True is_installed('hopefullythisisnotarealmodule') # Expected output: False ``` -------------------------------- ### Build jsonpickle Documentation Source: https://jsonpickle.github.io/_sources/contrib.rst.txt Generate the project's documentation using tox. ```bash tox -e docs ``` -------------------------------- ### Run jsonpickle Test Suite with Libraries Source: https://jsonpickle.github.io/contrib.html Create a testing environment that includes various JSON encoding and sample object libraries using tox. ```bash tox -e libs ``` -------------------------------- ### Get importable name of a class Source: https://jsonpickle.github.io/api.html Retrieves the fully qualified importable name of a given class. This is useful for ensuring that objects can be correctly reconstructed by name during unpickling. ```python class Example(object): pass ex = Example() importable_name(ex.__class__) == 'jsonpickle.util.Example' importable_name(type(25)) == 'builtins.int' importable_name(None.__class__) == 'builtins.NoneType' importable_name(False.__class__) == 'builtins.bool' importable_name(AttributeError) == 'builtins.AttributeError' ``` -------------------------------- ### Create Library Environment Without Running Tests Source: https://jsonpickle.github.io/contrib.html Set up the environment with necessary libraries using tox without executing the tests. ```bash tox -e libs --notest ``` -------------------------------- ### Serve jsonpickle Documentation Locally Source: https://jsonpickle.github.io/contrib.html Host the generated documentation locally using Python's http.server for browsing at http://localhost:8000. ```bash python -m http.server -d build/html ``` -------------------------------- ### Register gmpy Handlers for Ecdsa Source: https://jsonpickle.github.io/_sources/extensions.rst.txt Register gmpy handlers to prevent errors when serializing ecdsa module keys with gmpy2 installed. Import jsonpickle.ext.gmpy before calling register_handlers. ```python import jsonpickle.ext.gmpy as jsonpickle_gmpy jsonpickle_gmpy.register_handlers() ``` -------------------------------- ### Generate jsonpickle Documentation Source: https://jsonpickle.github.io/contrib.html Build the project's documentation using tox. The generated documentation will be available in the 'build/html' directory. ```bash tox -e docs ``` -------------------------------- ### Run jsonpickle Tests with Libraries Source: https://jsonpickle.github.io/_sources/contrib.rst.txt Create an environment to test against various JSON encoding and sample object libraries using tox. ```bash tox -e libs ``` -------------------------------- ### Run jsonpickle Test Suite with Libraries on Python 3.7 Source: https://jsonpickle.github.io/contrib.html Combine testing with libraries and a specific Python version (3.7) using tox. ```bash tox -e py37-libs ``` -------------------------------- ### Run jsonpickle Tests with Libraries on Python 3.7 Source: https://jsonpickle.github.io/_sources/contrib.rst.txt Test against libraries on Python 3.7 using tox. ```bash tox -e py37-libs ``` -------------------------------- ### jsonpickle.util.is_installed Source: https://jsonpickle.github.io/api.html Tests to see if a module is available on the sys.path. ```APIDOC ## jsonpickle.util.is_installed ### Description Tests to see if `module` is available on the sys.path. ### Parameters #### Path Parameters - **_module_** (string) - Required - The name of the module to check for. ``` -------------------------------- ### Run jsonpickle Test Suite Source: https://jsonpickle.github.io/contrib.html Execute the test suite using tox to ensure all tests pass. This is a prerequisite for merging code changes. ```bash tox ``` -------------------------------- ### Restore basic types with Unpickler Source: https://jsonpickle.github.io/api.html Demonstrates restoring basic Python types like strings and dictionaries using the Unpickler class. Ensure an Unpickler instance is created before calling restore. ```python >>> u = Unpickler() >>> u.restore('hello world') == 'hello world' True >>> u.restore({'key': 'value'}) == {'key': 'value'} True ``` -------------------------------- ### Load and Set Django's simplejson Backend Source: https://jsonpickle.github.io/api.html This snippet demonstrates how to load Django's bundled simplejson backend and set it as the preferred backend for jsonpickle. ```python jsonpickle.load_backend('django.util.simplejson', 'dumps', 'loads', ValueError)) jsonpickle.set_preferred_backend('django.util.simplejson') ``` -------------------------------- ### Clone jsonpickle Repository Source: https://jsonpickle.github.io/contrib.html Use this command to clone the jsonpickle project from GitHub. ```bash git clone https://github.com/jsonpickle/jsonpickle.git ``` -------------------------------- ### Load Python class from module path Source: https://jsonpickle.github.io/api.html Loads a Python class dynamically from its module and class name string. Handles valid paths and returns the class object. Returns None for non-existent paths. ```python >>> cls = loadclass('datetime.datetime') >>> cls.__name__ 'datetime' ``` ```python >>> loadclass('does.not.exist') ``` ```python >>> loadclass('builtins.int')() 0 ``` -------------------------------- ### Configure Decoder Options for a Backend Source: https://jsonpickle.github.io/api.html Associates decoder-specific options with a JSON backend. These options are passed to the backend's decode method. ```python set_decoder_options('simplejson', encoding='utf8', cls=JSONDecoder) ``` -------------------------------- ### JSONBackend Class Source: https://jsonpickle.github.io/api.html Manages encoding and decoding using various backends like simplejson, json, and ujson. ```APIDOC ## Class `jsonpickle.backend.JSONBackend` Manages encoding and decoding using various backends. It tries these modules in this order: simplejson, json, ujson. simplejson is a fast and popular backend and is tried first. json comes with Python and is tried second. ### `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. ### `dumps(_obj_ , _indent =None_, _separators =None_)` 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. ### `enable_fallthrough(_enable_)` 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. ### `encode(_obj_ , _indent =None_, _separators =None_)` 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(_dumps ='dumps'_, _loads ='loads'_, _loads_exc =ValueError_)` Load a JSON backend by name. This method loads a backend and sets up references to that backend’s loads/dumps functions and exception classes. Parameters: * **dumps** – is the name of the backend’s encode method. The method should take an object and return a string. Defaults to ‘dumps’. * **loads** – names the backend’s method for the reverse operation – returning a Python object from a string. * **loads_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. * **load** – names the backend’s ‘load’ method. * **dump** – names the backend’s ‘dump’ method. Rtype bool: True on success, False if the backend could not be loaded. ### `loads(_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. ### `remove_backend(_name_)` Remove all entries for a particular backend. ### `set_decoder_options(_name_ , _* args_, _** kwargs_)` Associate decoder-specific options with a decoder. After calling set_decoder_options, any calls to jsonpickle’s decode method will pass the supplied args and kwargs along to the appropriate backend’s decode method. For example: ``` set_decoder_options('simplejson', encoding='utf8', cls=JSONDecoder) ``` See the appropriate decoder’s documentation for details about the supported arguments and keyword arguments. ### `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) ``` See the appropriate encoder’s documentation for details about the supported arguments and keyword arguments. WARNING: If you pass sort_keys=True, and the object to encode contains `__slots__`, and you set `warn` to True, a TypeError will be raised! ### `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) then you must load the backend prior to calling set_preferred_backend. AssertionError is raised if the backend has not been loaded. ``` -------------------------------- ### Configuring simplejson for Decimal support Source: https://jsonpickle.github.io/api.html Configure the simplejson backend to handle Decimal instances during JSON encoding and decoding. This also sets `sort_keys=True` for the encoder and enables Decimal support for the decoder. ```python jsonpickle.set_encoder_options('simplejson', use_decimal=True, sort_keys=True) jsonpickle.set_decoder_options('simplejson', use_decimal=True) jsonpickle.set_preferred_backend('simplejson') ``` -------------------------------- ### Configure Encoder Options for a Backend Source: https://jsonpickle.github.io/api.html Associates encoder-specific options with a JSON backend. These options are passed to the backend's encode method. ```python set_encoder_options('simplejson', sort_keys=True, indent=4) ``` -------------------------------- ### jsonpickle.handlers.get Source: https://jsonpickle.github.io/api.html Looks up a handler by type reference or its fully qualified name. ```APIDOC ## jsonpickle.handlers.get ### Description Looks up a handler by type reference or its fully qualified name. If a direct match is not found, the search is performed over all handlers registered with base=True. ### Parameters - **cls_or_name** (type or str) - The type or its fully qualified name. - **default** (any) - Default value, if a matching handler is not found. ``` -------------------------------- ### jsonpickle.handlers.Registry.get Source: https://jsonpickle.github.io/api.html Looks up a registered handler by its type or fully qualified name. ```APIDOC ## jsonpickle.handlers.Registry.get ### Description Looks up a registered handler by its type or fully qualified name. If a direct match is not found, the search is performed over all handlers registered with `base=True`. ### Parameters #### Parameters - **cls_or_name** (type or str) - The type or its fully qualified name. - **default** (any) - Default value to return if a matching handler is not found. ``` -------------------------------- ### Run jsonpickle Test Suite with Specific Python Versions Source: https://jsonpickle.github.io/contrib.html Test the jsonpickle suite against specific Python versions, such as Python 2.7 and 3.7, using tox. ```bash tox -e py27,py37 ``` -------------------------------- ### Set Preferred JSON Backend Source: https://jsonpickle.github.io/api.html Sets a specific JSON backend to be used by jsonpickle. If the backend is not built-in, it must be loaded first. ```python set_preferred_backend('simplejson') ``` -------------------------------- ### Helper Functions Source: https://jsonpickle.github.io/api.html Provides utility functions for inspecting and loading Python objects from JSON representations. ```APIDOC ## Helper Functions ### `getargs(_obj_, _classes=None_)` Returns arguments suitable for `__new__()`. ### `has_tag(_obj_, _tag_)` Tests if an object is a dictionary and contains a specific key/tag. Example: ```python obj = {'test': 1} has_tag(obj, 'test') has_tag(obj, 'fail') has_tag(42, 'fail') ``` ### `has_tag_dict(_obj_, _tag_)` Alias for `has_tag`. ### `loadclass(_module_and_name_, _classes=None_)` Loads a class from its module and name. Example: ```python cls = loadclass('datetime.datetime') cls.__name__ loadclass('builtins.int')() ``` ### `loadrepr(_reprstr_)` Returns an instance of an object from its `repr()` string. **Warning**: This function is unsafe and uses `eval()`. Example: ```python obj = loadrepr('datetime/datetime.datetime.now()') obj.__class__.__name__ ``` ### `make_blank_classic(_cls_)` Creates a blank instance of a classic class. ``` -------------------------------- ### jsonpickle.load_backend Source: https://jsonpickle.github.io/_sources/api.rst.txt Loads an additional JSON backend for use with jsonpickle. This allows integrating custom or less common JSON libraries. ```APIDOC ## jsonpickle.load_backend ### Description Loads an additional JSON backend for use with jsonpickle. This function is useful for integrating custom or less common JSON libraries into the jsonpickle serialization process. ### Method load_backend ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### jsonpickle Backend Management Source: https://jsonpickle.github.io/index.html Allows for choosing, loading, and managing the JSON backends used by jsonpickle for serialization and deserialization. ```APIDOC ## jsonpickle Backend Management ### Description Allows for choosing, loading, and managing the JSON backends used by jsonpickle for serialization and deserialization. ### Methods - `set_preferred_backend(backend)`: Sets the preferred JSON backend. - `load_backend(backend)`: Loads a specific JSON backend. - `remove_backend(backend)`: Removes a JSON backend. - `set_encoder_options(**options)`: Sets encoder options for the preferred backend. - `set_decoder_options(**options)`: Sets decoder options for the preferred backend. ``` -------------------------------- ### Load Django's simplejson backend for jsonpickle Source: https://jsonpickle.github.io/_sources/api.rst.txt Use this to integrate jsonpickle with Django's bundled simplejson. Specify the module path, dump function, load function, and an exception type. ```python jsonpickle.load_backend('django.util.simplejson', 'dumps', 'loads', ValueError)) ``` -------------------------------- ### Set Django's simplejson as the preferred backend Source: https://jsonpickle.github.io/_sources/api.rst.txt After loading a backend, you can set it as the preferred one for jsonpickle to use by default. ```python jsonpickle.set_preferred_backend('django.util.simplejson') ``` -------------------------------- ### jsonpickle.load_backend Source: https://jsonpickle.github.io/api.html Loads a JSON backend by name, setting up references to its loads/dumps functions and exception classes. This allows jsonpickle to use custom or less common JSON libraries. ```APIDOC ## jsonpickle.load_backend(_dumps ='dumps'_, _loads ='loads'_, _loads_exc =ValueError_) ### Description Load a JSON backend by name. This method loads a backend and sets up references to that backend’s loads/dumps functions and exception classes. ### Method `load_backend(dumps='dumps', loads='loads', loads_exc=ValueError, load='load', dump='dump')` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python jsonpickle.load_backend('django.util.simplejson', 'dumps', 'loads', ValueError) ``` ### Response #### Success Response (bool) - True on success, False if the backend could not be loaded. #### Response Example ``` True ``` ### Parameters Details: - **dumps** (string) – is the name of the backend’s encode method. The method should take an object and return a string. Defaults to ‘dumps’. - **loads** (string) – names the backend’s method for the reverse operation – returning a Python object from a string. - **loads_exc** (string or exception class) – 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. - **load** (string) – names the backend’s ‘load’ method. - **dump** (string) – names the backend’s ‘dump’ method. ``` -------------------------------- ### Register NumPy Handlers Source: https://jsonpickle.github.io/_sources/extensions.rst.txt Enable the NumPy extension to serialize numpy-based data like sklearn models and numpy arrays. Ensure jsonpickle.ext.numpy is imported before registering. ```python import jsonpickle.ext.numpy as jsonpickle_numpy jsonpickle_numpy.register_handlers() ``` -------------------------------- ### Encoding Basic Python Types Source: https://jsonpickle.github.io/api.html Demonstrates encoding of simple Python types like strings, integers, and dictionaries into JSON strings. The `encode` function handles these types directly. ```python >>> encode('my string') == '"my string"' True >>> encode(36) == '36' True >>> encode({'foo': True}) == '{"foo": true}' True ``` -------------------------------- ### Check for __reduce__ or __reduce_ex__ methods Source: https://jsonpickle.github.io/api.html Tests if an object has the __reduce__ or __reduce_ex__ methods. These methods are important for custom serialization logic in Python's pickling mechanism. ```python jsonpickle.util.has_reduce(_obj_) ``` -------------------------------- ### Define a Python Class Source: https://jsonpickle.github.io/index.html Define a simple Python class that will be used for serialization. ```python class Thing(object): def __init__(self, name): self.name = name obj = Thing('Awesome') ``` -------------------------------- ### Flattening Basic Python Data Types with Pickler Source: https://jsonpickle.github.io/api.html Demonstrates how the Pickler.flatten method handles basic Python data types like strings, integers, floats, booleans, None, lists, tuples, and dictionaries. Tuples are shown to be represented with a special tag. ```python >>> p = Pickler() >>> p.flatten('hello world') == 'hello world' True >>> 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'} True ``` -------------------------------- ### jsonpickle Utility Functions Source: https://jsonpickle.github.io/index.html A collection of helper functions for various utility tasks within the jsonpickle library. ```APIDOC ## jsonpickle.util - Helper functions ### Description A collection of helper functions for various utility tasks within the jsonpickle library. ### Functions - Encoding/Decoding: `b64decode()`, `b64encode()`, `b85decode()`, `b85encode()` - Type Checking: `is_bytes()`, `is_dictionary()`, `is_list()`, `is_primitive()`, `is_unicode()`, etc. - Object Inspection: `has_method()`, `has_reduce()`, `importable_name()`, `is_picklable()`, etc. - Module/Name Translation: `translate_module_name()`, `untranslate_module_name()` ``` -------------------------------- ### jsonpickle.handlers.TextIOHandler Source: https://jsonpickle.github.io/api.html Custom handler for serializing file descriptors. ```APIDOC ## jsonpickle.handlers.TextIOHandler ### Description Serializes file descriptors as None because they cannot be reliably round-tripped. ### Methods #### flatten(_obj_, _data_) - **Description**: Flattens the object into a JSON-friendly form and writes the result to data. - **Parameters**: - **obj** (object) - The object to be serialized. - **data** (dict) - A partially filled dictionary which will contain the JSON-friendly representation of obj once this method has finished. #### restore(_data_) - **Description**: This method should never be called because flatten() returns None. ``` -------------------------------- ### jsonpickle.util.b64encode Source: https://jsonpickle.github.io/api.html Encodes binary data into base64 ASCII text. The input data must be bytes. ```APIDOC ## jsonpickle.util.b64encode ### Description Encodes binary data into base64 ASCII text. The input data must be bytes. ### Parameters #### Path Parameters - **_data_** (bytes) - Required - The binary data to encode. ``` -------------------------------- ### jsonpickle.handlers.BaseHandler Source: https://jsonpickle.github.io/api.html Base class for creating custom serialization handlers. Custom handlers must inherit from this class and implement `flatten` and `restore` methods. ```APIDOC ## jsonpickle.handlers.BaseHandler ### Description Base class for creating custom serialization handlers. Custom handlers must inherit from this class and implement `flatten` and `restore` methods. ### Methods #### flatten Flattens an object into a JSON-friendly representation. Parameters: - **obj** (object) - The object to be serialized. - **data** (dict) - A partially filled dictionary to store the JSON-friendly representation. #### restore Restores an object from its JSON-friendly representation. Parameters: - **data** (dict) - The JSON-friendly representation of the object. ``` -------------------------------- ### jsonpickle.set_preferred_backend Source: https://jsonpickle.github.io/_sources/api.rst.txt Sets the preferred JSON backend for encoding and decoding. jsonpickle tries backends in order: `simplejson`, `json`. ```APIDOC ## jsonpickle.set_preferred_backend ### Description Sets the preferred JSON backend for encoding and decoding operations. jsonpickle attempts to use backends in a specific order, and this function allows overriding that preference. ### Method set_preferred_backend ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### jsonpickle.set_preferred_backend Source: https://jsonpickle.github.io/api.html Sets the preferred JSON backend for jsonpickle. If a preferred backend is set, jsonpickle will attempt to use it before other available backends. This is useful for ensuring a specific JSON library is used. ```APIDOC ## jsonpickle.set_preferred_backend(_name_) ### Description Set the preferred json backend. If a preferred backend is set then jsonpickle tries to use it before any other backend. ### Method `set_preferred_backend(backend_name)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python set_preferred_backend('simplejson') ``` ### Response None ERROR HANDLING: - AssertionError is raised if the backend has not been loaded. ``` -------------------------------- ### jsonpickle Low Level API - Unpickler Source: https://jsonpickle.github.io/index.html Offers lower-level control for converting JSON-compatible dictionaries back into Python objects. ```APIDOC ## jsonpickle.unpickler - JSON-compatible dict to Python ### Description Offers lower-level control for converting JSON-compatible dictionaries back into Python objects. ### Methods - `decode()`: A convenience function that uses the Unpickler to decode a JSON string. - `Unpickler.register_classes(classes)`: Registers classes for deserialization. - `Unpickler.reset()`: Resets the unpickler's internal state. - `Unpickler.restore(obj)`: Restores a Python object from a JSON-compatible dictionary. ``` -------------------------------- ### jsonpickle.set_decoder_options Source: https://jsonpickle.github.io/_sources/api.rst.txt Sets specific decoding options for the JSON decoder. ```APIDOC ## jsonpickle.set_decoder_options ### Description Sets specific decoding options for the JSON decoder used by jsonpickle. This allows fine-tuning the deserialization process. ### Method set_decoder_options ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### jsonpickle.util.b85encode Source: https://jsonpickle.github.io/api.html Encodes binary data into base85 ASCII text. The input data must be bytes. ```APIDOC ## jsonpickle.util.b85encode ### Description Encodes binary data into base85 ASCII text. The input data must be bytes. ### Parameters #### Path Parameters - **_data_** (bytes) - Required - The binary data to encode. ``` -------------------------------- ### jsonpickle.util Helper Functions Source: https://jsonpickle.github.io/api.html The jsonpickle.util module provides a set of helper functions to inspect objects. These functions can determine if an object is a class, a picklable object, a primitive type, a sequence, a set, a tuple, or a unicode string, among other checks. They also include utility functions for item retrieval and module name translation. ```APIDOC ## jsonpickle.util Helper Functions ### Description This section lists and describes the utility functions available in the `jsonpickle.util` module. These functions are designed to assist in determining the nature and characteristics of Python objects, particularly in the context of pickling and serialization. ### Functions - **`is_not_class()`**: Checks if an object is not a class. - **`is_object()`**: Checks if an object is an instance of a class. - **`is_picklable()`**: Determines if an object can be pickled. - **`is_primitive()`**: Identifies if an object is a primitive data type. - **`is_readonly()`**: Checks if an object's attributes are read-only. - **`is_reducible()`**: Determines if an object can be reduced (e.g., for serialization). - **`is_reducible_sequence_subclass()`**: Checks if an object is a subclass of a reducible sequence. - **`is_sequence()`**: Identifies if an object is a sequence. - **`is_sequence_subclass()`**: Checks if an object is a subclass of a sequence. - **`is_set()`**: Determines if an object is a set. - **`is_tuple()`**: Checks if an object is a tuple. - **`is_type()`**: Identifies if an object is a type. - **`is_unicode()`**: Checks if an object is a unicode string. - **`itemgetter()`**: Returns a callable that fetches an item from its operand. - **`items()`**: Returns a view object that displays a dictionary's key-value tuple pairs. - **`translate_module_name()`**: Translates a module name, potentially for serialization purposes. - **`untranslate_module_name()`**: Reverses the module name translation. ``` -------------------------------- ### jsonpickle.util.translate_module_name Source: https://jsonpickle.github.io/api.html Renames builtin modules to a consistent, modern module name for cross-version compatibility. ```APIDOC ## jsonpickle.util.translate_module_name ### Description Renames builtin modules to a consistent, modern module name for cross-version compatibility. This is used so that references to Python's builtins module can be loaded in both Python 2 and 3. It remaps to the "__builtin__" name and unmaps it when importing. It also maps the Python 2 exceptions module to builtins. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **str** (str) - The translated module name. ### Response Example None ``` -------------------------------- ### Verify Recreated Object Source: https://jsonpickle.github.io/index.html Assert that the deserialized object has the same data as the original object. ```python assert obj.name == thawed.name ``` -------------------------------- ### Load object from repr string with loadrepr Source: https://jsonpickle.github.io/api.html Reconstructs a Python object from its string representation using eval(). This function is unsafe and should be used with caution due to potential security risks. ```python >>> obj = loadrepr('datetime/datetime.datetime.now()') >>> obj.__class__.__name__ 'datetime' ``` -------------------------------- ### jsonpickle.set_encoder_options Source: https://jsonpickle.github.io/_sources/api.rst.txt Sets specific encoding options for the JSON encoder. ```APIDOC ## jsonpickle.set_encoder_options ### Description Sets specific encoding options for the JSON encoder used by jsonpickle. This allows fine-tuning the serialization process. ### Method set_encoder_options ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Registering a Custom Handler for Numpy Generic Types Source: https://jsonpickle.github.io/api.html Illustrates how to register a custom handler for numpy.generic types to control their serialization behavior, specifically to exclude the dtype when converting numpy arrays to JSON. ```python jsonpickle.register( numpy.generic, UnpicklableNumpyGenericHandler, base=True ) ``` -------------------------------- ### Encoding with Max Depth Source: https://jsonpickle.github.io/api.html Shows how to limit the depth of nested structures during JSON encoding using the `max_depth` parameter. This prevents excessively long or complex JSON outputs. ```python >>> encode({'foo': [1, 2, [3, 4]]}, max_depth=1) '{"foo": "[1, 2, [3, 4]]"}' ``` -------------------------------- ### Decoding JSON Strings to Python Objects Source: https://jsonpickle.github.io/api.html Illustrates decoding JSON strings back into Python objects using the `decode` function. This is the reverse operation of encoding. ```python >>> decode('"my string"') == 'my string' True >>> decode('36') 36 ``` -------------------------------- ### jsonpickle Low Level API - Pickler Source: https://jsonpickle.github.io/index.html Provides lower-level control over the process of converting Python objects into JSON-compatible dictionaries. ```APIDOC ## jsonpickle.pickler - Python to JSON-compatible dict ### Description Provides lower-level control over the process of converting Python objects into JSON-compatible dictionaries. ### Classes and Methods - `Pickler`: - `flatten()`: Converts a Python object to a JSON-compatible dictionary. - `reset()`: Resets the pickler's internal state. - `encode()`: A convenience function that uses the Pickler to encode an object. ``` -------------------------------- ### jsonpickle Custom Serialization Handlers Source: https://jsonpickle.github.io/index.html Enables customization of how specific Python types are serialized and deserialized by providing custom handler classes. ```APIDOC ## jsonpickle.handlers Custom Serialization Handlers ### Description Enables customization of how specific Python types are serialized and deserialized by providing custom handler classes. ### Handlers - `ArrayHandler`: Handles array-like objects. - `BaseHandler`: Base class for custom handlers. - `DatetimeHandler`: Handles datetime objects. - `LockHandler`: Handles lock objects. - `QueueHandler`: Handles queue objects. - `RegexHandler`: Handles regular expression objects. - `TextIOHandler`: Handles text I/O objects. - `UUIDHandler`: Handles UUID objects. ### Registry Methods - `get(type)`: Retrieves the handler for a given type. - `register(type, handler)`: Registers a custom handler for a type. - `unregister(type)`: Unregisters the handler for a type. ``` -------------------------------- ### jsonpickle.util.is_list_like Source: https://jsonpickle.github.io/api.html Checks if an object is list-like. ```APIDOC ## jsonpickle.util.is_list_like ### Description Checks if an object is list-like. ### Parameters #### Path Parameters - **_obj_** (any) - Required - The object to check. ``` -------------------------------- ### Check if a key exists in object's slots Source: https://jsonpickle.github.io/api.html Returns true if a key exists in the object's __slots__. If __slots__ is absent, it returns a specified default value. ```python jsonpickle.util.in_slots(_obj_ , _key_ , _default =False_) ``` -------------------------------- ### jsonpickle.util.is_not_class Source: https://jsonpickle.github.io/api.html Determines if the object is not a class or a class instance. ```APIDOC ## jsonpickle.util.is_not_class ### Description Determines if the object is not a class or a class instance. Used for serializing properties. ### Parameters #### Path Parameters - **_obj_** (any) - Required - The object to check. ``` -------------------------------- ### jsonpickle.util.itemgetter Source: https://jsonpickle.github.io/api.html Retrieves an item from an object using a getter. ```APIDOC ## jsonpickle.util.itemgetter ### Description Retrieves an item from an object using a getter. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **any** (any) - The retrieved item. ### Response Example None ``` -------------------------------- ### Registering a Custom Handler using a Decorator Source: https://jsonpickle.github.io/api.html This snippet shows how to register a custom handler for a class using the @handles decorator provided by BaseHandler. This is a convenient way to associate a handler with a specific class. ```python from jsonpickle.handlers import BaseHandler @BaseHandler.handles class MyCustomClass: def __reduce__(self): # ... implementation to define how to reduce the object pass ``` -------------------------------- ### jsonpickle.util.importable_name Source: https://jsonpickle.github.io/api.html Returns the importable name of a class. ```APIDOC ## jsonpickle.util.importable_name ### Description Returns the importable name of a class. ### Parameters #### Path Parameters - **_cls_** (type) - Required - The class to get the importable name for. ``` -------------------------------- ### jsonpickle.util.b64decode Source: https://jsonpickle.github.io/api.html Decodes a base64 encoded payload. The payload must be ASCII text. ```APIDOC ## jsonpickle.util.b64decode ### Description Decodes a base64 encoded payload. The payload must be ASCII text. ### Parameters #### Path Parameters - **_payload_** (string) - Required - The base64 encoded string to decode. ``` -------------------------------- ### Registering a Custom Handler Manually Source: https://jsonpickle.github.io/api.html This snippet demonstrates how to manually register a custom handler for a specific class using the jsonpickle.handlers.register() function. This method is useful when the @handles decorator is not suitable. ```python import jsonpickle from jsonpickle.handlers import BaseHandler class MyCustomHandler(BaseHandler): def flatten(self, obj, data): # ... implementation to flatten the object pass def restore(self, data): # ... implementation to restore the object pass jsonpickle.handlers.register(MyCustomClass, MyCustomHandler) ``` -------------------------------- ### jsonpickle.util.is_type Source: https://jsonpickle.github.io/api.html Returns True if the provided object is a reference to a type. ```APIDOC ## jsonpickle.util.is_type ### Description Returns True if the provided object is a reference to a type. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **bool** (bool) - True if the object is a type reference, False otherwise. ### Response Example ```json { "example": "True" } ``` ``` -------------------------------- ### Check if an object is picklable Source: https://jsonpickle.github.io/api.html Determines if a given object can be pickled. This is a preliminary check to avoid pickling errors. ```python import os is_picklable('os', os) # Expected output: True def foo(): pass is_picklable('foo', foo) # Expected output: True is_picklable('foo', lambda: None) # Expected output: False ``` -------------------------------- ### jsonpickle.util.items Source: https://jsonpickle.github.io/api.html Returns items from an object, with an option to exclude specific items. ```APIDOC ## jsonpickle.util.items ### Description Returns items from an object, with an option to exclude specific items. This is useful when dict.items() is not sufficient due to the 'exclude' parameter. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **list** (list) - A list of items from the object. ### Response Example None ``` -------------------------------- ### Registering a custom handler for numpy.generic Source: https://jsonpickle.github.io/api.html Register a custom handler for numpy.generic types to control how they are pickled. This is useful for ensuring compatibility or specific serialization behavior, especially when `unpicklable` is set to `False`. ```python import numpy jsonpickle.register( numpy.generic, UnpicklableNumpyGenericHandler, base=True ) ``` -------------------------------- ### jsonpickle High Level API Source: https://jsonpickle.github.io/index.html Provides the main interface for encoding Python objects into JSON strings and decoding JSON strings back into Python objects. ```APIDOC ## jsonpickle High Level API ### Description Provides the main interface for encoding Python objects into JSON strings and decoding JSON strings back into Python objects. ### Methods - `encode()`: Serializes a Python object into a JSON string. - `decode()`: Deserializes a JSON string into a Python object. ``` -------------------------------- ### jsonpickle.util.has_reduce Source: https://jsonpickle.github.io/api.html Tests if __reduce__ or __reduce_ex__ exists in the object or its class MRO. ```APIDOC ## jsonpickle.util.has_reduce ### Description Tests if __reduce__ or __reduce_ex__ exists in the object or its class MRO (excluding 'object'). ### Returns A tuple of booleans (has_reduce, has_reduce_ex). ``` -------------------------------- ### jsonpickle.handlers.UUIDHandler Source: https://jsonpickle.github.io/api.html Custom handler for serializing uuid.UUID objects. ```APIDOC ## jsonpickle.handlers.UUIDHandler ### Description Serializes uuid.UUID objects. ### Methods #### flatten(_obj_, _data_) - **Description**: Flattens the object into a JSON-friendly form and writes the result to data. - **Parameters**: - **obj** (object) - The object to be serialized. - **data** (dict) - A partially filled dictionary which will contain the JSON-friendly representation of obj once this method has finished. #### restore(_data_) - **Description**: Restores an object of the registered type from the JSON-friendly representation obj and returns it. ``` -------------------------------- ### Check if a key exists in object's dictionary Source: https://jsonpickle.github.io/api.html Returns true if a key exists in the object's __dict__. If the __dict__ is absent, it returns a specified default value. ```python jsonpickle.util.in_dict(_obj_ , _key_ , _default =False_) ``` -------------------------------- ### jsonpickle.util.is_object Source: https://jsonpickle.github.io/api.html Returns True if obj is a reference to an object instance. ```APIDOC ## jsonpickle.util.is_object ### Description Returns True if obj is a reference to an object instance. ### Parameters #### Path Parameters - **_obj_** (any) - Required - The object to check. ``` -------------------------------- ### jsonpickle.util.is_picklable Source: https://jsonpickle.github.io/api.html Return True if an object can be pickled. ```APIDOC ## jsonpickle.util.is_picklable ### Description Return True if an object can be pickled. ### Parameters #### Path Parameters - **_name_** (string) - Required - The name of the object. - **_value_** (any) - Required - The object to check for picklability. ``` -------------------------------- ### Unpickler Class Source: https://jsonpickle.github.io/api.html The Unpickler class is used to manage the process of restoring flattened objects into their original Python state. It can be configured with various options to control deserialization behavior. ```APIDOC ## class Unpickler ### Description Manages the deserialization of JSON-compatible dictionaries into Python objects. ### Methods #### `__init__(_backend=None, _keys=False, _safe=True, _v1_decode=False, _on_missing='ignore', _handle_readonly=False)` Initializes an Unpickler instance with specified backend and decoding options. #### `register_classes(_classes_)` Registers one or more classes with the Unpickler for deserialization. Parameters: `classes` (sequence or class): A sequence or single class to register. #### `reset()` Resets the internal state of the Unpickler. #### `restore(_obj_, _reset=True, _classes=None_)` Restores a flattened object to its original Python state. Handles basic builtin types directly. Example: ```python u = Unpickler() u.restore('hello world') == 'hello world' u.restore({'key': 'value'}) == {'key': 'value'} ``` ``` -------------------------------- ### jsonpickle.decode Source: https://jsonpickle.github.io/api.html Converts a JSON string back into a Python object. Supports various options for backend selection, context, key handling, safety, class availability, version compatibility, and handling of missing classes or read-only objects. ```APIDOC ## `jsonpickle.decode` ### Description Converts a JSON string back into a Python object. Supports various options for backend selection, context, key handling, safety, class availability, version compatibility, and handling of missing classes or read-only objects. ### Parameters * **backend** – If set to an instance of jsonpickle.backend.JSONBackend, jsonpickle will use that backend for deserialization. * **context** – Supply a pre-built Pickler or Unpickler object to the jsonpickle.encode and jsonpickle.decode machinery instead of creating a new instance. The context represents the currently active Pickler and Unpickler objects when custom handlers are invoked by jsonpickle. * **keys** – If set to True then jsonpickle will decode non-string dictionary keys into python objects via the jsonpickle protocol. * **reset** – Custom pickle handlers that use the Pickler.flatten method or jsonpickle.encode function must call encode with reset=False in order to retain object references during pickling. This flag is not typically used outside of a custom handler or __getstate__ implementation. * **safe** – If set to `False`, use of `eval()` for backwards-compatible (pre-0.7.0) deserialization of repr-serialized objects is enabled. Defaults to `True`. The default value was `False` in jsonpickle v3 and changed to `True` in jsonpickle v4. Warning `eval()` is used when set to `False` and is not secure against malicious inputs. You should avoid setting `safe=False`. * **classes** – If set to a single class, or a sequence (list, set, tuple) of classes, then the classes will be made available when constructing objects. If set to a dictionary of class names to class objects, the class object will be provided to jsonpickle to deserialize the class name into. This can be used to give jsonpickle access to local classes that are not available through the global module import scope, and the dict method can be used to deserialize encoded objects into a new class. * **v1_decode** – If set to True it enables you to decode objects serialized in jsonpickle v1. Please do not attempt to re-encode the objects in the v1 format! Version 2’s format fixes issue #255, and allows dictionary identity to be preserved through an encode/decode cycle. * **on_missing** – If set to ‘error’, it will raise an error if the class it’s decoding is not found. If set to ‘warn’, it will warn you in said case. If set to a non-awaitable function, it will call said callback function with the class name (a string) as the only parameter. Strings passed to on_missing are lowercased automatically. * **handle_readonly** – If set to True, the Unpickler will handle objects encoded with ‘handle_readonly’ properly. Do not set this flag for objects not encoded with ‘handle_readonly’ set to True. ### Request Example ```python >>> decode('"my string"') == 'my string' True >>> decode('36') 36 ``` ``` -------------------------------- ### jsonpickle.util.untranslate_module_name Source: https://jsonpickle.github.io/api.html Reverses the module name translation applied by translate_module_name, making module names importable in the current Python version. ```APIDOC ## jsonpickle.util.untranslate_module_name ### Description Reverses the module name translation applied by translate_module_name, making module names importable in the current Python version. This function is the reverse operation of translate_module_name(). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **str** (str) - The untranslated module name. ### Response Example None ``` -------------------------------- ### Check if an object is an instance of a class Source: https://jsonpickle.github.io/api.html Returns True if the object is an instance of a class. This helps differentiate between class definitions and their instantiated objects. ```python is_object(1) # Expected output: True is_object(object()) # Expected output: True is_object(lambda x: 1) # Expected output: False ``` -------------------------------- ### jsonpickle.util.in_slots Source: https://jsonpickle.github.io/api.html Checks if a key exists in an object's __slots__. ```APIDOC ## jsonpickle.util.in_slots ### Description Returns true if the key exists in obj.__slots__; false otherwise. If obj.__slots__ is absent, returns the default value. ### Parameters #### Path Parameters - **_obj_** (object) - Required - The object to check. - **_key_** (string) - Required - The key to look for. - **_default_** (boolean) - Optional - The default value to return if __slots__ is absent. Defaults to False. ``` -------------------------------- ### jsonpickle.util.b85decode Source: https://jsonpickle.github.io/api.html Decodes a base85 encoded payload. The payload must be ASCII text. ```APIDOC ## jsonpickle.util.b85decode ### Description Decodes a base85 encoded payload. The payload must be ASCII text. ### Parameters #### Path Parameters - **_payload_** (string) - Required - The base85 encoded string to decode. ``` -------------------------------- ### Check if an object is a primitive type Source: https://jsonpickle.github.io/api.html Helper method to identify basic data types like strings, integers, floats, booleans, and None. Primitive types are often handled directly during serialization. ```python is_primitive(3) # Expected output: True is_primitive([4,4]) # Expected output: False ``` -------------------------------- ### Check if an object is a sequence subclass Source: https://jsonpickle.github.io/api.html Verifies if the provided object is an instance of a subclass of a sequence type. This is useful for custom list-like objects. ```python >>> class Temp(list): pass >>> is_sequence_subclass(Temp()) True ```