MCPcopy
hub / github.com/django/django / json_script

Function json_script

django/utils/html.py:100–117  ·  view source on GitHub ↗

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.

(value, element_id=None, encoder=None)

Source from the content-addressed store, hash-verified

98
99
100def json_script(value, element_id=None, encoder=None):
101 """
102 Escape all the HTML/XML special characters with their unicode escapes, so
103 value is safe to be output anywhere except for inside a tag attribute. Wrap
104 the escaped JSON in a script tag.
105 """
106 from django.core.serializers.json import DjangoJSONEncoder
107
108 json_str = json.dumps(value, cls=encoder or DjangoJSONEncoder).translate(
109 _json_script_escapes
110 )
111 if element_id:
112 template = '<script id="{}" type="application/json">{}</script>'
113 args = (element_id, mark_safe(json_str))
114 else:
115 template = '<script type="application/json">{}</script>'
116 args = (mark_safe(json_str),)
117 return format_html(template, *args)
118
119
120def conditional_escape(text):

Callers 3

test_json_scriptMethod · 0.90

Calls 3

mark_safeFunction · 0.90
format_htmlFunction · 0.85
dumpsMethod · 0.45

Tested by 3

test_json_scriptMethod · 0.72