=============
JSON Handling
=============
Tet provides enhanced JSON handling capabilities that go beyond Python's standard JSON module, with built-in security features and custom type adapters.
Safe JavaScript Serialization
=============================
One of Tet's key security features is safe JSON serialization that prevents XSS attacks when embedding JSON data in HTML pages.
The Problem
-----------
Standard JSON serialization can be unsafe when embedded in HTML:
.. code-block:: python
import json
# This data contains potentially dangerous characters
user_data = {"message": ""}
# Standard JSON - UNSAFE for HTML embedding
unsafe_json = json.dumps(user_data)
# Result: {"message": ""}
When embedded in HTML, this could execute malicious JavaScript:
.. code-block:: text
"};
The Solution: js_safe_dumps
---------------------------
Tet's ``js_safe_dumps`` function escapes dangerous characters:
.. code-block:: python
from tet.util.json import js_safe_dumps
user_data = {"message": ""}
# Safe for embedding in HTML/JavaScript
safe_json = js_safe_dumps(user_data)
# Result: {"message": "\\u003c/script\\u003e\\u003cscript\\u003ealert('XSS')\\u003c/script\\u003e"}
Escaped Characters
------------------
``js_safe_dumps`` escapes these dangerous characters:
* ``<`` → ``\\u003c`` (Prevents tag injection)
* ``>`` → ``\\u003e`` (Prevents tag injection)
* ``/`` → ``\\u002f`` (Prevents script tag closing)
* ``&`` → ``\\u0026`` (Prevents HTML entity issues)
* ``\u2028`` → ``\\u2028`` (Line separator - can break JavaScript)
* ``\u2029`` → ``\\u2029`` (Paragraph separator - can break JavaScript)
Usage in Templates
------------------
Use the safe JSON in your templates:
.. code-block:: html
``$literal(...)`` outputs the value without HTML-escaping in the Tonnikala template engine, which is what you want since ``js_safe_dumps`` has already produced a string that is safe to embed in a ``