Skip to content

Instantly share code, notes, and snippets.

@vergenzt
Created November 18, 2025 18:02
Show Gist options
  • Select an option

  • Save vergenzt/ce0a33bbb31b37d13221f1424be89926 to your computer and use it in GitHub Desktop.

Select an option

Save vergenzt/ce0a33bbb31b37d13221f1424be89926 to your computer and use it in GitHub Desktop.
type JsonVal = bool | int | float | str | None | dict[str, JsonVal] | list[JsonVal]
def escape_jinja_in_leaf_strs(val: JsonVal) -> JsonVal:
"""
Escape Jinja template markers in leaf strings.
Assuming that any strings at leaf nodes of the given JSON object, sanitize them so that:
(a) Jinja processing doesn't fail, and
(b) the result after such processing is equivalent to the input `val`.
"""
match val:
case dict():
return {k: escape_jinja_in_leaf_strs(v) for k, v in val.items()}
case list():
return [escape_jinja_in_leaf_strs(v) for v in val]
case str():
if "{{" in val or "{%" in val:
return "{%raw%}" + val + "{%endraw%}"
else:
return val
case _:
return val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment