CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-sphinxawesome-theme

An awesome theme for the Sphinx documentation generator with enhanced features, custom code highlighting, and modern responsive design

Overview
Eval results
Files

json-serialization.mddocs/

JSON Serialization

Custom JSON serialization system designed to handle the complex template context data in Sphinx themes, including non-serializable Jinja2 functions and theme-specific objects. This module provides a robust serialization layer for JSON output builders and theme data persistence.

Capabilities

Custom JSON Encoder

Specialized JSON encoder that handles theme-specific objects and non-serializable template data.

class AwesomeJSONEncoder(json.JSONEncoder):
    """
    Custom JSON encoder for everything in the template context.
    
    Provides safe serialization by returning empty strings for
    non-serializable objects instead of raising exceptions.
    """
    
    def default(self, obj: Any) -> str:
        """
        Return an empty string for anything that's not serializable by default.
        
        This prevents JSON serialization errors when template context
        contains Jinja2 functions or other non-serializable objects.
        
        Parameters:
        - obj (Any): Object to serialize
        
        Returns:
        str: Empty string for non-serializable objects
        """

JSON File Operations

Enhanced JSON file operations that automatically use the custom encoder.

def dump(obj: Any, fp: IO[str], *args: Any, **kwargs: Any) -> None:
    """
    Dump JSON into file using the custom encoder.
    
    Automatically applies AwesomeJSONEncoder to handle theme-specific
    objects and non-serializable template context data.
    
    Parameters:
    - obj (Any): Object to serialize
    - fp (IO[str]): File-like object to write to
    - *args: Additional positional arguments for json.dump
    - **kwargs: Additional keyword arguments for json.dump
    """

def dumps(obj: Any, *args: Any, **kwargs: Any) -> str:
    """
    Convert object to JSON string using the custom encoder.
    
    Parameters:
    - obj (Any): Object to serialize
    - *args: Additional positional arguments for json.dumps
    - **kwargs: Additional keyword arguments for json.dumps
    
    Returns:
    str: JSON string representation
    """

JSON Deserialization

Standard JSON deserialization functions for completeness.

def load(*args: Any, **kwargs: Any) -> Any:
    """
    De-serialize JSON from file.
    
    Standard JSON loading with consistent interface.
    
    Parameters:
    - *args: Positional arguments for json.load
    - **kwargs: Keyword arguments for json.load
    
    Returns:
    Any: Deserialized Python object
    """

def loads(*args: Any, **kwargs: Any) -> Any:
    """
    De-serialize JSON from string.
    
    Parameters:
    - *args: Positional arguments for json.loads
    - **kwargs: Keyword arguments for json.loads
    
    Returns:
    Any: Deserialized Python object
    """

Integration with Sphinx

JSON Builder Configuration

The JSON serialization system integrates with Sphinx's JSON HTML builder:

# In theme setup
JSONHTMLBuilder.out_suffix = ".json"
JSONHTMLBuilder.implementation = jsonimpl
JSONHTMLBuilder.indexer_format = jsonimpl

This configuration:

  • Sets proper file extension for JSON output
  • Uses custom serialization implementation
  • Applies custom formatting for search indexing

Template Context Serialization

The custom encoder handles common non-serializable objects in Sphinx template contexts:

# Example template context objects that need custom handling
context = {
    "theme_options": {...},           # Serializable
    "pathto": <function pathto>,      # Non-serializable - becomes ""
    "hasdoc": <function hasdoc>,      # Non-serializable - becomes ""
    "sidebar_links": [...],           # Serializable
    "custom_jinja_filter": <filter>,  # Non-serializable - becomes ""
}

Usage Examples

Basic JSON Serialization

import sphinxawesome_theme.jsonimpl as json

# Serialize theme data
theme_data = {
    "version": "5.3.2",
    "options": theme_options,
    "non_serializable": some_function
}

# Safe serialization - non-serializable objects become empty strings
json_string = json.dumps(theme_data)

File-Based Serialization

# Write theme configuration to file
with open("theme_config.json", "w") as f:
    json.dump(theme_options, f, indent=2)

Integration with Sphinx Builders

# The JSON builder automatically uses this implementation
# when configured in the theme setup function

Error Handling

Non-Serializable Objects

The custom encoder provides graceful handling of problematic objects:

# Instead of raising TypeError
try:
    json.dumps(non_serializable_object)
except TypeError:
    # This would happen with standard json module
    pass

# With custom encoder - returns empty string safely
result = jsonimpl.dumps(non_serializable_object)  # Returns '""'

Consistent Interface

All functions maintain the same interface as the standard json module:

# Drop-in replacement for standard json module
import sphinxawesome_theme.jsonimpl as json

# All standard json operations work identically
data = json.loads('{"key": "value"}')
text = json.dumps(data)

Performance Considerations

Encoder Efficiency

The custom encoder is optimized for template context serialization:

  • Minimal overhead for serializable objects
  • Fast fallback for non-serializable objects
  • No exception handling overhead during serialization

Memory Usage

The encoder design minimizes memory usage:

  • No object introspection for standard types
  • Immediate string return for non-serializable objects
  • No intermediate object creation

Use Cases

Theme Configuration Export

Export complete theme configuration for debugging or transfer:

# Export all theme settings
config_data = {
    "theme_options": theme_options,
    "html_context": filtered_context,
    "build_info": build_metadata
}

json.dump(config_data, config_file, indent=2)

Search Index Generation

Generate JSON data for client-side search functionality:

# Create search index data
search_data = {
    "pages": page_metadata,
    "sections": section_data,
    "keywords": keyword_index
}

search_json = json.dumps(search_data, separators=(',', ':'))

API Documentation

Serialize API documentation data for external tools:

# Export documentation structure
api_data = {
    "modules": module_info,
    "classes": class_definitions,
    "functions": function_signatures
}

json.dump(api_data, api_file)

Install with Tessl CLI

npx tessl i tessl/pypi-sphinxawesome-theme

docs

code-highlighting.md

deprecated-options.md

html-postprocessing.md

index.md

json-serialization.md

logo-management.md

template-functions.md

theme-builder.md

theme-configuration.md

toc-manipulation.md

tile.json