<script type="application/json" id="myJSONData">
{
"name": "John Doe",
"age": 30
}
</script>
<script>
const data = JSON.parse(document.getElementById('myJSONData').textContent);
console.log(data.name + " is " + data.age); // John Doe is 30
</script>
Note: The JSON data must exist literally within the script element. If you try using a src attribute to request it from elsewhere, the response will not be available via textContent or any other mechanism [0], and at that point you just need to fetch/ajax/xhr it.[0] https://stackoverflow.com/questions/17124713/read-response-o...
<script> parses its contents as text, whereas <template> parses as DOM. This means you don't have to escape `<`, just `</script>`.
Myself and some browser engineers been working on proposals to allow for inline modules, including JSON, that are importable into other modules via regular import statements.
This is why I recommend the "-json" type - so it doesn't collide with a future native "json" type.
I wouldn't use application/json just in case browsers start supporting that and it has different semantics than whatever custom thing you might do, causing a webcompat issue when the native feature rolls out.
Although with JSON, it's pretty unlikely that there would be any differing semantics. JSON modules in JS are just JSON blocks with no special additions and no named exports. That's what inline versions would be as well.
Any CSP-allowed other script can read that application/json script tag and decode it, but it is no different than reading any other data it has access to like any other html element or attribute.
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.
Here's another take, just a short list of replacements. Interestingly, "&" is also escaped: https://pkg.go.dev/encoding/json#HTMLEscape
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.