Note: This question is very close to Embedding JSON objects in script tags, but the responses to that question provides what I already know (that in JSON /
== \/
). I want to know how to do that escaping.
The HTML spec prohibits closed HTML tags anywhere within a <script>
element. So, this causes parse errors:
<script>
var assets = [{
"asset_created": null,
"asset_id": "575155948f7d4c4ebccb02d4e8f84d2f",
"body": "<script></script>"
}];
</script>
In my case, I'm generating the invalid situation by rendering a JSON string inside a Django template, i.e.:
<script>
var assets = {{ json_string }};
</script>
I know that JSON parses \/
the same as /
, so if I can just escape my closing HTML tags in the JSON string, I'll be good. But, I'm not sure of the best way to do this.
My naive approach would just be this:
json_string = '[{"asset_created": null, "asset_id": "575155948f7d4c4ebccb02d4e8f84d2f", "body": "<script></script>"}]'
escaped_json_string = json_string.replace('</', r'<\/')
Is there a better way? Or any gotchas that I'm overlooking?