How to avoid closing '/' in HTML tags in JSON using Python?

Note. This question is very close to Embedding JSON objects in script tags , but the answers to this question provide what I already know (which in JSON /== \/). I want to know how to do this.

The HTML specification forbids closed HTML tags anywhere in an element <script>. Thus, this leads to parsing errors:

<script>
var assets = [{
  "asset_created": null, 
  "asset_id": "575155948f7d4c4ebccb02d4e8f84d2f", 
  "body": "<script></script>"
}];
</script>

In my case, I create an invalid situation by creating a JSON string inside a Django template, i.e.:

<script>
var assets = {{ json_string }};
</script>

I know that JSON parses the \/same way /, so if I can just avoid my closing HTML tags in the JSON string, I will be fine. But I'm not sure how to do this.

My naive approach would be this:

json_string = '[{"asset_created": null, "asset_id": "575155948f7d4c4ebccb02d4e8f84d2f", "body": "<script></script>"}]'
escaped_json_string = json_string.replace('</', r'<\/')

? , ?

+5
1

, . JSON simplejson JSONEncoderForHTML, . , pip easy_install, . - :

import simplejson
asset_json=simplejson.loads(json_string)
encoded=simplejson.encoder.JSONEncoderForHTML().encode(assets_json)

encoded :

'{"asset_id": "575155948f7d4c4ebccb02d4e8f84d2f", "body": "\\u003cscript\\u003e\\u003c/script\\u003e", "asset_created": null}'

, , .

loads , JSON . , DJango, , JSON simplejson:

simplejson.dumps(your_object_to_encode, cls=simplejson.encoder.JSONEncoderForHTML)

script CDATA:

<script>
//<![CDATA[
var assets = [{
  "asset_created": null, 
  "asset_id": "575155948f7d4c4ebccb02d4e8f84d2f", 
  "body": "<script></script>"
}];
//]]>
</script>

, . escape-.

+6

All Articles