Skip to main content

json_script

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.

def json_script(
value: any,
element_id: string = None,
encoder: json.JSONEncoder = None
) - > string

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.

Parameters

NameTypeDescription
valueanyThe Python object to be serialized into JSON format.
element_idstring = NoneAn optional HTML ID attribute to assign to the generated script tag for easier selection via JavaScript.
encoderjson.JSONEncoder = NoneA custom JSON encoder class used to serialize the provided value; defaults to DjangoJSONEncoder if not specified.

Returns

TypeDescription
stringA safe-to-render HTML script tag containing the JSON-serialized data, optionally including an ID attribute.