<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.
Just do this
Replace < with \x3C or \u003C in JSON strings.
with or in JSON strings. In PHP, use json_encode($data, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES) for safe JSON in <script> tags.
for safe JSON in tags. In WordPress, use wp_json_encode with the same flags.
You don’t have to take my word for it, the HTML standard recommends this type of escaping:
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.
What’s so gnarly about a script tag?
Script tags are used to embed other languages in HTML. The most common example is JavaScript:
... continue reading