An encoder that produces JSON safe to embed in HTML. To embed JSON content in, say, a script tag on a web page, the characters &, < and > should be escaped. They cannot be escaped with the usual entities (e.g. &) because they are not expanded within tags. This clas
| 397 | |
| 398 | |
| 399 | class JSONEncoderForHTML(JSONEncoder): |
| 400 | """An encoder that produces JSON safe to embed in HTML. |
| 401 | |
| 402 | To embed JSON content in, say, a script tag on a web page, the |
| 403 | characters &, < and > should be escaped. They cannot be escaped |
| 404 | with the usual entities (e.g. &) because they are not expanded |
| 405 | within <script> tags. |
| 406 | |
| 407 | This class also escapes the line separator and paragraph separator |
| 408 | characters U+2028 and U+2029, irrespective of the ensure_ascii setting, |
| 409 | as these characters are not valid in JavaScript strings (see |
| 410 | http://timelessrepo.com/json-isnt-a-javascript-subset). |
| 411 | """ |
| 412 | |
| 413 | def encode(self, o): |
| 414 | # Override JSONEncoder.encode because it has hacks for |
| 415 | # performance that make things more complicated. |
| 416 | chunks = self.iterencode(o) |
| 417 | if self.ensure_ascii: |
| 418 | return ''.join(chunks) |
| 419 | else: |
| 420 | return u''.join(chunks) |
| 421 | |
| 422 | def iterencode(self, o): |
| 423 | chunks = super(JSONEncoderForHTML, self).iterencode(o) |
| 424 | for chunk in chunks: |
| 425 | chunk = chunk.replace('&', '\\u0026') |
| 426 | chunk = chunk.replace('<', '\\u003c') |
| 427 | chunk = chunk.replace('>', '\\u003e') |
| 428 | |
| 429 | if not self.ensure_ascii: |
| 430 | chunk = chunk.replace(u'\u2028', '\\u2028') |
| 431 | chunk = chunk.replace(u'\u2029', '\\u2029') |
| 432 | |
| 433 | yield chunk |
| 434 | |
| 435 | |
| 436 | def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…