I'm thinking about embedding arbitrary JSON in the DOM like this:
<script type="application/json" id="stuff">
{
"unicorns": "awesome",
"abc": [1, 2, 3]
}
</script>
This is similar to the way one might store an arbitrary HTML template in the DOM for later use with a JavaScript template engine. In this case, we could later retrieve the JSON and parse it with:
var stuff = JSON.parse(document.getElementById('stuff').innerHTML);
This works, but is it the best way? Does this violate any best practice or standard?
Note: I'm not looking for alternatives to storing JSON in the DOM, I've already decided that's the best solution for the particular problem I'm having. I'm just looking for the best way to do it.
var
in javascript? – Krizz</script><script>alert()</script><script>
inside your JSON object, you'll get surprises. This is not safe unless you sanitize the data first. – silviot