CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-jsonpickle

Python library for encoding/decoding any Python object to/from JSON

Pending
Overview
Eval results
Files

backend-system.mddocs/

Backend Management System

Pluggable JSON encoder/decoder backend system supporting multiple JSON libraries with configuration options and fallback mechanisms.

Capabilities

JSONBackend Class

Core backend management class that handles multiple JSON encoder/decoder implementations.

class JSONBackend:
    def __init__(self):
        """Initialize backend manager with default backends."""
        
    def encode(self, obj):
        """
        Encode object using the active backend.
        
        Parameters:
        - obj: Object to encode
        
        Returns:
        JSON string
        """
        
    def decode(self, s):
        """
        Decode JSON string using the active backend.
        
        Parameters:
        - s: JSON string to decode
        
        Returns:
        Decoded Python object
        """
        
    def dumps(self, obj):
        """Alias for encode() - json.dumps compatibility"""
        
    def loads(self, s):
        """Alias for decode() - json.loads compatibility"""
        
    def load_backend(self, name, dumps=None, loads=None, 
                     encoder_options=None, decoder_options=None):
        """
        Load and register a new JSON backend.
        
        Parameters:
        - name: Backend name
        - dumps: Function for encoding objects
        - loads: Function for decoding strings
        - encoder_options: Default encoder options
        - decoder_options: Default decoder options
        """
        
    def remove_backend(self, name):
        """
        Remove a registered backend.
        
        Parameters:
        - name: Backend name to remove
        """
        
    def set_preferred_backend(self, name):
        """
        Set the preferred backend to use.
        
        Parameters:
        - name: Backend name ('json', 'simplejson', 'ujson', etc.)
        """
        
    def set_encoder_options(self, name, **options):
        """
        Configure encoder options for a backend.
        
        Parameters:
        - name: Backend name
        - **options: Encoder-specific options
        """
        
    def set_decoder_options(self, name, **options):
        """
        Configure decoder options for a backend.
        
        Parameters:
        - name: Backend name
        - **options: Decoder-specific options
        """
        
    def enable_fallthrough(self, enable=True):
        """
        Enable/disable fallthrough to next backend on failure.
        
        Parameters:
        - enable: Whether to enable fallthrough
        """
        
    def backend_encode(self, name, obj, indent=None, separators=None):
        """
        Encode object using a specific backend.
        
        Parameters:
        - name: Backend name to use
        - obj: Object to encode
        - indent: JSON indentation level
        - separators: JSON separators for compact output
        
        Returns:
        JSON string
        """
        
    def backend_decode(self, name, string):
        """
        Decode JSON string using a specific backend.
        
        Parameters:
        - name: Backend name to use
        - string: JSON string to decode
        
        Returns:
        Decoded Python object
        """

Module-Level Backend Functions

Convenience functions for backend management at the module level.

def set_preferred_backend(name):
    """Set the preferred JSON backend"""

def set_encoder_options(name, **options):
    """Set encoder options for a backend"""

def set_decoder_options(name, **options):
    """Set decoder options for a backend"""

def load_backend(name, **kwargs):
    """Load and register a new backend"""

def remove_backend(name):
    """Remove a registered backend"""

def enable_fallthrough(enable=True):
    """Enable/disable backend fallthrough"""

Basic Backend Usage:

import jsonpickle

# Set preferred backend
jsonpickle.set_preferred_backend('simplejson')

# Configure encoder options for pretty printing
jsonpickle.set_encoder_options('json', indent=2, sort_keys=True)

# Configure decoder options
jsonpickle.set_decoder_options('json', strict=False)

# Enable fallthrough to next backend on failure
jsonpickle.enable_fallthrough(True)

Supported Backends

jsonpickle supports several JSON backends with automatic detection:

Standard Library json

# Built-in Python json module (default)
jsonpickle.set_preferred_backend('json')

# Common encoder options
jsonpickle.set_encoder_options('json',
    indent=2,           # Pretty printing
    sort_keys=True,     # Sort dictionary keys
    separators=(',', ':'),  # Compact output
    ensure_ascii=False  # Allow unicode
)

simplejson

# High-performance JSON library
jsonpickle.set_preferred_backend('simplejson')

# simplejson-specific options
jsonpickle.set_encoder_options('simplejson',
    use_decimal=True,   # Support Decimal objects
    namedtuple_as_object=True,  # Handle namedtuples
    indent=2
)

jsonpickle.set_decoder_options('simplejson',
    use_decimal=True,   # Preserve Decimal precision
    parse_float=float   # Custom float parsing
)

ujson

# Ultra-fast JSON library
jsonpickle.set_preferred_backend('ujson')

# ujson options (limited compared to others)
jsonpickle.set_encoder_options('ujson',
    indent=2,
    sort_keys=True
)

Custom Backend Implementation

Load custom JSON backends for specialized needs.

import jsonpickle

# Custom encoder/decoder functions
def custom_dumps(obj, **kwargs):
    # Custom encoding logic
    return custom_json_encode(obj)

def custom_loads(s, **kwargs):
    # Custom decoding logic
    return custom_json_decode(s)

# Register custom backend
jsonpickle.load_backend(
    'custom',
    dumps=custom_dumps,
    loads=custom_loads,
    encoder_options={'custom_option': True},
    decoder_options={'parse_mode': 'strict'}
)

# Use the custom backend
jsonpickle.set_preferred_backend('custom')

Backend Configuration Examples

High-Precision Decimal Support

import jsonpickle
from decimal import Decimal

# Configure for decimal precision
jsonpickle.set_preferred_backend('simplejson')
jsonpickle.set_encoder_options('simplejson', use_decimal=True, sort_keys=True)
jsonpickle.set_decoder_options('simplejson', use_decimal=True)

# Now Decimal objects preserve precision
value = Decimal('123.456789012345678901234567890')
json_str = jsonpickle.encode(value)
restored = jsonpickle.decode(json_str)
assert value == restored

Performance Optimization

import jsonpickle

# Use ujson for maximum speed
jsonpickle.set_preferred_backend('ujson')

# Compact output for minimal size
jsonpickle.set_encoder_options('ujson', sort_keys=False)

# Enable fallthrough for compatibility
jsonpickle.enable_fallthrough(True)

Development/Debugging Configuration

import jsonpickle

# Pretty printing for readability
jsonpickle.set_preferred_backend('json')
jsonpickle.set_encoder_options('json',
    indent=2,
    sort_keys=True,
    ensure_ascii=False
)

Backend Selection Strategy

jsonpickle automatically selects backends in order of availability:

  1. Preferred backend (if set and available)
  2. simplejson (if installed)
  3. ujson (if installed)
  4. json (standard library fallback)

Use enable_fallthrough(True) to automatically try the next backend if the current one fails.

Global Backend Instance

# The global backend instance used by jsonpickle
from jsonpickle.backend import json

# Access backend methods directly
json.set_preferred_backend('simplejson')
json.encode({'key': 'value'})
json.decode('{"key": "value"}')

Error Handling

Backend operations may raise various exceptions:

  • ImportError: When a backend module is not available
  • ValueError: When invalid options are provided
  • TypeError: When unsupported data types are encountered
  • Backend-specific errors: Depending on the JSON library used

Always handle these appropriately in production code.

Install with Tessl CLI

npx tessl i tessl/pypi-jsonpickle

docs

advanced-classes.md

backend-system.md

core-serialization.md

extensions.md

handler-system.md

index.md

tile.json