Hacker News new | ask | show | jobs
by lioeters 291 days ago
About embedding JSON in a script tag, I recently read an article on the risk of a closing </script> tag within the JSON that could break it.

Safe JSON in script tags: How not to break a site - https://sirre.al/2025/08/06/safe-json-in-script-tags-how-not...

As with all untrusted content, depending on where the JSON string comes from, sanitizing the output is worth considering.

2 comments

Great article! I suppose a similar (yet different) precaution would be needed in data-* attributes or any other part of an HTML document.
That article was pretty complicated; I appreciate the historical understanding but frankly web legacy is too complex to bother with "why" too much, in the end so many things just don't make sense and are historical accidents.

Here's another take, just a short list of replacements. Interestingly, "&" is also escaped: https://pkg.go.dev/encoding/json#HTMLEscape

That's a helpful summary of what's necessary to make JSON safe to embed in script tags.

I agree the "why" is too long of a story, an accumulation of supposedly logical decisions that led up to the ball of quirks. It's too much to remember. Exactly the kind of thing that should be delegated to a specialized function made and maintained by experts.