Works exactly like :func:`dumps` but is safe for use in `` `` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain
(obj, dumper=None, **kwargs)
| 543 | |
| 544 | |
| 545 | def htmlsafe_json_dumps(obj, dumper=None, **kwargs): |
| 546 | """Works exactly like :func:`dumps` but is safe for use in ``<script>`` |
| 547 | tags. It accepts the same arguments and returns a JSON string. Note that |
| 548 | this is available in templates through the ``|tojson`` filter which will |
| 549 | also mark the result as safe. Due to how this function escapes certain |
| 550 | characters this is safe even if used outside of ``<script>`` tags. |
| 551 | |
| 552 | The following characters are escaped in strings: |
| 553 | |
| 554 | - ``<`` |
| 555 | - ``>`` |
| 556 | - ``&`` |
| 557 | - ``'`` |
| 558 | |
| 559 | This makes it safe to embed such strings in any place in HTML with the |
| 560 | notable exception of double quoted attributes. In that case single |
| 561 | quote your attributes or HTML escape it in addition. |
| 562 | """ |
| 563 | if dumper is None: |
| 564 | dumper = json.dumps |
| 565 | rv = dumper(obj, **kwargs) \ |
| 566 | .replace(u'<', u'\\u003c') \ |
| 567 | .replace(u'>', u'\\u003e') \ |
| 568 | .replace(u'&', u'\\u0026') \ |
| 569 | .replace(u"'", u'\\u0027') |
| 570 | return Markup(rv) |
| 571 | |
| 572 | |
| 573 | @implements_iterator |