Modern high-performance serialization utilities for Python
Low-level, high-performance JSON serialization implemented in C, providing the fastest possible JSON encoding and decoding operations. This module serves as the underlying engine for srsly's main JSON API functions.
Convert Python objects to JSON strings with high performance and fine-grained control over output formatting.
def dumps(obj, indent=0, ensure_ascii=True, double_precision=9, encode_html_chars=False, escape_forward_slashes=True):
"""
Serialize Python object to JSON string with high performance.
Parameters:
- obj: Python object to serialize
- indent (int): Number of spaces for indentation (0 for compact)
- ensure_ascii (bool): Escape non-ASCII characters as Unicode escapes
- double_precision (int): Maximum number of decimal places for floats
- encode_html_chars (bool): Encode HTML characters (< > &) as Unicode escapes
- escape_forward_slashes (bool): Escape forward slash characters
Returns:
str: JSON string representation
"""
def encode(obj, indent=0, ensure_ascii=True, double_precision=9, encode_html_chars=False, escape_forward_slashes=True):
"""
Alias for dumps() - serialize Python object to JSON string.
Parameters:
- obj: Python object to serialize
- indent (int): Number of spaces for indentation (0 for compact)
- ensure_ascii (bool): Escape non-ASCII characters as Unicode escapes
- double_precision (int): Maximum number of decimal places for floats
- encode_html_chars (bool): Encode HTML characters (< > &) as Unicode escapes
- escape_forward_slashes (bool): Escape forward slash characters
Returns:
str: JSON string representation
"""Parse JSON strings into Python objects with high performance and precision control.
def loads(data, precise_float=False):
"""
Deserialize JSON string to Python object with high performance.
Parameters:
- data (str | bytes): JSON string or bytes to deserialize
- precise_float (bool): Use high-precision float decoder for exact decimal representation
Returns:
Any: Deserialized Python object
"""
def decode(data, precise_float=False):
"""
Alias for loads() - deserialize JSON string to Python object.
Parameters:
- data (str | bytes): JSON string or bytes to deserialize
- precise_float (bool): Use high-precision float decoder for exact decimal representation
Returns:
Any: Deserialized Python object
"""Direct file I/O operations for JSON data with optimal performance.
def dump(obj, fp, indent=0, ensure_ascii=True, double_precision=9, encode_html_chars=False, escape_forward_slashes=True):
"""
Serialize Python object directly to file with high performance.
Parameters:
- obj: Python object to serialize
- fp: File-like object to write to
- indent (int): Number of spaces for indentation (0 for compact)
- ensure_ascii (bool): Escape non-ASCII characters as Unicode escapes
- double_precision (int): Maximum number of decimal places for floats
- encode_html_chars (bool): Encode HTML characters (< > &) as Unicode escapes
- escape_forward_slashes (bool): Escape forward slash characters
Returns:
None
"""
def load(fp, precise_float=False):
"""
Deserialize JSON directly from file with high performance.
Parameters:
- fp: File-like object to read from
- precise_float (bool): Use high-precision float decoder for exact decimal representation
Returns:
Any: Deserialized Python object
"""import srsly.ujson as ujson
# Ultra-fast serialization
data = {
"name": "Performance Test",
"scores": [95.7, 87.3, 92.8],
"metadata": {"version": 1.0, "optimized": True}
}
# Compact JSON with maximum performance
json_compact = ujson.dumps(data)
print(json_compact)
# Formatted JSON with custom precision
json_formatted = ujson.dumps(data, indent=2, double_precision=2)
print(json_formatted)import srsly.ujson as ujson
# Financial data requiring high precision
financial_data = {
"account": "12345",
"balance": 12345.67890123456, # High precision decimal
"transactions": [
{"amount": 100.12345, "date": "2023-01-01"},
{"amount": -50.98765, "date": "2023-01-02"}
]
}
# Use precise_float for exact decimal handling
json_str = ujson.dumps(financial_data, double_precision=15)
restored_data = ujson.loads(json_str, precise_float=True)
print(f"Original balance: {financial_data['balance']}")
print(f"Restored balance: {restored_data['balance']}")import srsly.ujson as ujson
# Data containing HTML characters
html_data = {
"content": "<div>Hello & welcome to our site!</div>",
"script": "if (x < 5 && y > 10) { return true; }",
"url": "https://example.com/path"
}
# Encode HTML characters for safe embedding
html_safe = ujson.dumps(html_data, encode_html_chars=True)
print("HTML-safe JSON:", html_safe)
# Control forward slash escaping
no_slash_escape = ujson.dumps(html_data, escape_forward_slashes=False)
print("No slash escaping:", no_slash_escape)import srsly.ujson as ujson
# Large dataset
large_dataset = {
"version": "1.0",
"data": [{"id": i, "value": i * 1.5, "label": f"item_{i}"} for i in range(10000)]
}
# Direct file writing for optimal performance
with open("large_dataset.json", "w") as f:
ujson.dump(large_dataset, f, indent=2)
# Direct file reading
with open("large_dataset.json", "r") as f:
loaded_dataset = ujson.load(f, precise_float=True)
print(f"Dataset version: {loaded_dataset['version']}")
print(f"Data points: {len(loaded_dataset['data'])}")import srsly.ujson as ujson
# Data with Unicode characters
unicode_data = {
"name": "José García",
"city": "São Paulo",
"greeting": "Hello 世界",
"emoji": "🌟⭐✨"
}
# Keep Unicode characters (faster, smaller output)
unicode_json = ujson.dumps(unicode_data, ensure_ascii=False)
print("Unicode preserved:", unicode_json)
# Escape to ASCII (safer for legacy systems)
ascii_json = ujson.dumps(unicode_data, ensure_ascii=True)
print("ASCII escaped:", ascii_json)