Ultra fast JSON encoder and decoder for Python with C extensions providing drop-in compatibility with the standard json module
npx @tessl/cli install tessl/pypi-ujson@5.11.0UltraJSON 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.
pip install ujsonimport ujsonimport 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)UltraJSON is implemented as a Python C extension module, providing exceptional performance through:
json module exactly, allowing seamless replacement without code changesujson.c, objToJSON.c, JSONtoObj.c) that integrates with Python's C APIThis architecture delivers significant performance gains over pure Python implementations while maintaining full compatibility with Python's standard JSON interface and data types.
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
"""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
"""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.
"""Version information for the ujson package.
__version__: str
"""Version string of the ujson package (e.g., '5.11.0')"""UltraJSON provides significant performance improvements over Python's standard json module:
# 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"'# 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é"'data = {"users": [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]}
pretty = ujson.dumps(data, indent=2)
# Results in formatted JSON with 2-space indentationimport 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)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}")