HTML utilities

django_orjson.html.json_script(value, element_id=None, default=<function default>, option=None)[source]

Escape all the HTML/XML special characters with their unicode escapes, so value is safe to be output anywhere except for inside a tag attribute. Wrap the escaped JSON in a script tag.

An orjson-powered version of Django’s json_script() utility. It serializes value with orjson.dumps(), escapes HTML/XML special characters, and wraps the result in a <script type="application/json"> tag.

from django_orjson.html import json_script

json_script({"key": "value"}, "data")
Parameters:
  • value (Any) – The object to serialize.

  • element_id (str | None) – An optional id attribute for the <script> tag.

  • default (Callable[[Any], Any]) – Passes through to orjson; defaults to django_orjson.default().

  • option (int | None) – Passes through to orjson.

Return type:

SafeString

json_script template filter

A template filter equivalent to Django’s built-in json_script, using the function above. In your templates:

{% load django_orjson %}
{{ data|json_script:"my-data" }}