<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\u003Cin JSON strings. - In PHP, use
json_encode($data, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES)for safe JSON in<script>tags. - In WordPress, use
wp_json_encodewith 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.
(more…)