File: jsonify.py

package info (click to toggle)
python-django-jsonfield 1.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 204 kB
  • sloc: python: 568; makefile: 6
file content (28 lines) | stat: -rw-r--r-- 662 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import json

from django import template
from django.utils.safestring import mark_safe
from jsonfield.utils import TZAwareJSONEncoder

register = template.Library()


@register.filter
def jsonify(value):
    # If we have a queryset, then convert it into a list.
    if getattr(value, 'all', False):
        value = list(value)

    json_str = json.dumps(value, cls=TZAwareJSONEncoder)

    unsafe_chars = {
        '&': '\\u0026',
        '<': '\\u003c',
        '>': '\\u003e',
        '\u2028': '\\u2028',
        '\u2029': '\\u2029',
    }
    for (unsafe, safe) in unsafe_chars.items():
        json_str = json_str.replace(unsafe, safe)

    return json_str