I was wondering, are template elements a good place to store json data in the page to be consumed by js?
replies(4):
<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...
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.