or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-ujson

Ultra fast JSON encoder and decoder for Python with C extensions providing drop-in compatibility with the standard json module

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/ujson@5.11.x

To install, run

npx @tessl/cli install tessl/pypi-ujson@5.11.0

index.mddocs/

UltraJSON (ujson)

UltraJSON is an ultra-fast JSON encoder and decoder written in pure C with Python bindings. It provides drop-in compatibility with Python's standard json module while delivering significantly better performance for both encoding and decoding operations.

Package Information

  • Package Name: ujson
  • Language: Python (C extension)
  • Installation: pip install ujson
  • Python Support: 3.9+

Core Imports

import ujson

Basic Usage

import ujson

# Basic encoding (Python object to JSON string)
data = {"name": "John", "age": 30, "items": [1, 2, 3]}
json_string = ujson.dumps(data)
print(json_string)  # '{"name":"John","age":30,"items":[1,2,3]}'

# Basic decoding (JSON string to Python object)
parsed_data = ujson.loads(json_string)
print(parsed_data)  # {'name': 'John', 'age': 30, 'items': [1, 2, 3]}

# File operations
with open('data.json', 'w') as f:
    ujson.dump(data, f)

with open('data.json', 'r') as f:
    loaded_data = ujson.load(f)

# Advanced encoding options
safe_html = ujson.dumps("<script>alert('hi')</script>", encode_html_chars=True)
pretty_json = ujson.dumps(data, indent=4)
ascii_only = ujson.dumps("café", ensure_ascii=True)

Architecture

UltraJSON is implemented as a Python C extension module, providing exceptional performance through:

  • C Implementation Core: The encoding and decoding engines are written in pure C, bypassing Python's interpreter overhead for JSON processing operations
  • Memory-Optimized Parsing: Direct memory manipulation and efficient buffer management eliminate unnecessary Python object allocations during parsing
  • Drop-in Compatibility: Python module interface mirrors the standard json module exactly, allowing seamless replacement without code changes
  • Extension Module Structure: Built as a compiled extension (ujson.c, objToJSON.c, JSONtoObj.c) that integrates with Python's C API
  • Double-conversion Integration: Uses the Google double-conversion library for high-performance floating-point number serialization

This architecture delivers significant performance gains over pure Python implementations while maintaining full compatibility with Python's standard JSON interface and data types.

Capabilities

JSON Encoding Functions

Converts Python objects to JSON strings with various formatting and safety options.

def encode(
    obj,
    ensure_ascii=True,
    encode_html_chars=False,
    escape_forward_slashes=True,
    sort_keys=False,
    indent=0,
    allow_nan=True,
    reject_bytes=False,
    default=None,
    separators=None
):
    """
    Convert Python object to JSON string.
    
    Args:
        obj: Any Python object to serialize
        ensure_ascii (bool): Limit output to ASCII and escape extended characters (default: True)
        encode_html_chars (bool): Encode unsafe HTML characters as Unicode escapes (default: False)
        escape_forward_slashes (bool): Control forward slash escaping (default: True)
        sort_keys (bool): Sort dictionary keys in output (default: False)
        indent (int): Pretty print indentation, 0 = disabled (default: 0)
        allow_nan (bool): Allow NaN/Infinity values (default: True)
        reject_bytes (bool): Raise TypeError on bytes objects (default: False)
        default (callable, optional): Function to serialize arbitrary types
        separators (tuple, optional): (item_separator, key_separator) tuple
    
    Returns:
        str: JSON string representation
    """

def dumps(
    obj,
    ensure_ascii=True,
    encode_html_chars=False,
    escape_forward_slashes=True,
    sort_keys=False,
    indent=0,
    allow_nan=True,
    reject_bytes=False,
    default=None,
    separators=None
):
    """
    Alias for encode(). Convert Python object to JSON string.
    
    Args: Identical to encode()
    
    Returns:
        str: JSON string representation
    """

def dump(
    obj,
    fp,
    *,
    ensure_ascii=True,
    encode_html_chars=False,
    escape_forward_slashes=True,
    sort_keys=False,
    indent=0,
    allow_nan=True,
    reject_bytes=False,
    default=None,
    separators=None
):
    """
    Serialize object to file-like object.
    
    Args:
        obj: Any Python object to serialize
        fp: File-like object with write() method that accepts strings (SupportsWrite[str])
        ensure_ascii (bool): Limit output to ASCII and escape extended characters (default: True)
        encode_html_chars (bool): Encode unsafe HTML characters as Unicode escapes (default: False)
        escape_forward_slashes (bool): Control forward slash escaping (default: True)
        sort_keys (bool): Sort dictionary keys in output (default: False)
        indent (int): Pretty print indentation, 0 = disabled (default: 0)
        allow_nan (bool): Allow NaN/Infinity values (default: True)
        reject_bytes (bool): Raise TypeError on bytes objects (default: False)
        default (callable | None): Function to serialize arbitrary types (default: None)
        separators (tuple[str, str] | None): (item_separator, key_separator) tuple (default: None)
    
    Returns:
        None
    """

JSON Decoding Functions

Parses JSON strings and files back into Python objects.

def decode(s):
    """
    Parse JSON string to Python object.
    
    Args:
        s (str | bytes | bytearray): JSON string to parse
    
    Returns:
        Any: Python object (dict, list, str, int, float, bool, None)
    
    Raises:
        JSONDecodeError: If JSON string is invalid
    """

def loads(s):
    """
    Alias for decode(). Parse JSON string to Python object.
    
    Args:
        s (str | bytes | bytearray): JSON string to parse
    
    Returns:
        Any: Python object (dict, list, str, int, float, bool, None)
    
    Raises:
        JSONDecodeError: If JSON string is invalid
    """

def load(fp):
    """
    Parse JSON from file-like object.
    
    Args:
        fp: File-like object with read() method that returns strings, bytes, or bytearrays (SupportsRead[str | bytes | bytearray])
    
    Returns:
        Any: Python object (dict, list, str, int, float, bool, None)
    
    Raises:
        JSONDecodeError: If JSON content is invalid
    """

Error Handling

Exception raised when JSON parsing fails.

class JSONDecodeError(ValueError):
    """
    Exception raised when JSON decoding fails.
    
    Inherits from ValueError for compatibility with standard json module.
    Raised by decode(), loads(), and load() functions on invalid JSON.
    """

Module Information

Version information for the ujson package.

__version__: str
"""Version string of the ujson package (e.g., '5.11.0')"""

Performance Features

UltraJSON provides significant performance improvements over Python's standard json module:

  • Ultra-fast C implementation: Written in pure C for maximum speed
  • Drop-in compatibility: Direct replacement for standard json module functions
  • Memory efficient: Optimized memory usage for large data structures
  • Wide type support: Handles all standard Python types plus decimal.Decimal

Encoding Options Usage

HTML Safety

# Encode unsafe HTML characters for safe embedding
html_safe = ujson.dumps("<script>alert('xss')</script>", encode_html_chars=True)
# Result: '"\\u003cscript\\u003ealert(\\u0027xss\\u0027)\\u003c\\/script\\u003e"'

ASCII Control

# Force ASCII-only output (default behavior)
ascii_json = ujson.dumps("café", ensure_ascii=True)
# Result: '"caf\\u00e9"'

# Allow UTF-8 characters (smaller output)
utf8_json = ujson.dumps("café", ensure_ascii=False)
# Result: '"café"'

Pretty Printing

data = {"users": [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]}
pretty = ujson.dumps(data, indent=2)
# Results in formatted JSON with 2-space indentation

Custom Serialization

import datetime

def date_handler(obj):
    if isinstance(obj, datetime.datetime):
        return obj.isoformat()
    raise TypeError(f"Object {obj} is not JSON serializable")

data = {"timestamp": datetime.datetime.now()}
json_str = ujson.dumps(data, default=date_handler)

Error Handling Patterns

import ujson

# Handle decoding errors
try:
    data = ujson.loads('{"invalid": json}')
except ujson.JSONDecodeError as e:
    print(f"JSON decode error: {e}")

# Handle encoding errors with custom types
try:
    result = ujson.dumps({"obj": object()})
except TypeError as e:
    print(f"Cannot serialize object: {e}")