Safe JSON in script tags: How not to break a site

submited by
Style Pass
2025-08-08 23:00:05

<script> tags follow unintuitive parsing rules that can break a webpage in surprising ways. Fortunately, it’s relatively straightforward to escape JSON for script tags.

The easiest and safest … is to always escape an ASCII case-insensitive match for “<!--” as “\x3C!--“, “<script” as “\x3Cscript“, and “</script” as “\x3C/script“…

This post will dive deep into the exotic script tag parsing rules in order to understand how they work and why this is the appropriate way to escape JSON.

In fact, script tags can contain any language (not necessarily JavaScript) or even arbitrary data. In order to support this behavior, script tags have special parsing rules. For the most part, the browser accepts whatever is inside the script tag until it finds the script close tag </script>1.

Oops! We can see that </script> was part of a JavaScript string, but the browser is just parsing the HTML. This script element closes prematurely, resulting in the following tree:

Leave a Comment
Related Posts