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

core-serialization.mddocs/

Core Serialization Functions

Essential functions for converting Python objects to/from JSON strings. These are the primary public APIs that most users will interact with for basic serialization needs.

Capabilities

Object Encoding

Converts Python objects to JSON strings with extensive configuration options for controlling serialization behavior.

def encode(
    value,
    unpicklable=True,
    make_refs=True,
    keys=False,
    max_depth=None,
    reset=True,
    backend=None,
    warn=False,
    context=None,
    max_iter=None,
    use_decimal=False,
    numeric_keys=False,
    use_base85=False,
    fail_safe=None,
    indent=None,
    separators=None,
    include_properties=False,
    handle_readonly=False,
) -> str:
    """
    Return a JSON formatted representation of value, a Python object.

    Parameters:
    - value: The Python object to encode
    - unpicklable (bool): If False, creates simpler JSON without restoration metadata
    - make_refs (bool): If False, disables referencing support for id()-identical objects
    - keys (bool): If True, encodes non-string dictionary keys instead of coercing to strings
    - max_depth (int): Maximum recursion depth before using repr()
    - reset (bool): Whether to reset the pickler state (typically True)
    - backend (JSONBackend): Custom JSON backend to use
    - warn (bool): If True, warns when objects cannot be pickled
    - context (Pickler): Pre-built Pickler object to use
    - max_iter (int): Maximum items to consume from iterators
    - use_decimal (bool): Allow Decimal instances to pass-through
    - numeric_keys (bool): Leave numeric keys as-is (backend dependent)
    - use_base85 (bool): Use base85 encoding for binary data
    - fail_safe (callable): Function to call when encoding fails
    - indent (int): JSON pretty-printing indentation
    - separators (tuple): JSON separators for compact output
    - include_properties (bool): Include property attributes in serialization
    - handle_readonly (bool): Handle read-only attributes specially

    Returns:
    JSON string representation of the object
    """

Usage Example:

import jsonpickle

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 30)

# Basic encoding
json_str = jsonpickle.encode(person)

# Encoding without restoration metadata (simpler JSON)
simple_json = jsonpickle.encode(person, unpicklable=False)

# Pretty-printed JSON
formatted_json = jsonpickle.encode(person, indent=2)

# Encoding with custom depth limit
shallow_json = jsonpickle.encode(person, max_depth=1)

Object Decoding

Converts JSON strings back to Python objects with safety and compatibility options.

def decode(
    string,
    backend=None,
    context=None,
    keys=False,
    reset=True,
    safe=True,
    classes=None,
    v1_decode=False,
    on_missing='ignore',
    handle_readonly=False,
):
    """
    Convert a JSON string into a Python object.

    Parameters:
    - string (str): JSON string to decode
    - backend (JSONBackend): Custom JSON backend to use
    - context (Unpickler): Pre-built Unpickler object to use
    - keys (bool): If True, decodes non-string dictionary keys
    - reset (bool): Whether to reset the unpickler state
    - safe (bool): If False, enables eval() for backwards compatibility (insecure)
    - classes (class/list/dict): Classes to make available during construction
    - v1_decode (bool): Enable v1 format compatibility
    - on_missing (str/callable): How to handle missing classes ('ignore', 'warn', 'error', or function)
    - handle_readonly (bool): Handle read-only attributes properly

    Returns:
    Restored Python object
    """

Usage Example:

import jsonpickle

# Basic decoding
json_str = '{"py/object": "person.Person", "name": "Alice", "age": 30}'
person = jsonpickle.decode(json_str)

# Safe decoding with local classes
local_classes = {'Person': Person}
person = jsonpickle.decode(json_str, classes=local_classes)

# Decoding with error handling for missing classes
person = jsonpickle.decode(json_str, on_missing='warn')

# Custom missing class handler
def handle_missing(class_name):
    print(f"Class {class_name} not found")
    return None

person = jsonpickle.decode(json_str, on_missing=handle_missing)

JSON Compatibility Functions

Aliases providing compatibility with the standard json module's interface.

dumps = encode
loads = decode

Usage Example:

import jsonpickle

# Use like json.dumps/loads
obj = {'name': 'Alice', 'items': [1, 2, 3]}
json_str = jsonpickle.dumps(obj)
restored = jsonpickle.loads(json_str)

Error Handling

The decode function may raise ClassNotFoundError when a class cannot be found during unpickling, depending on the on_missing parameter setting.

Security Considerations

  • Always use safe=True (default) when decoding untrusted data
  • The unpicklable=False option creates simpler, safer JSON output
  • Consider validating input data before decoding
  • Never decode data from untrusted sources without proper validation

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