[Django]-Django: Parse JSON in my template using Javascript

70👍

You could use the built-in json module:

>>> import json
>>> geodata = [ ( "Here", (1003,3004) ), ("There", (1.2,1.3)) ]
>>> json.dumps(geodata)
'[["Here", [1003, 3004]], ["There", [1.2, 1.3]]]'

You can then simply embed the resulting string inside a javascript script:

<script type='text/javascript'>
var geodata = {{ geodata|safe }};
</script>
👤adamk

28👍

Okay, I solved my problem and would like to answer my own question. I figured it would be better for the other users here.

First, get the file here: http://www.JSON.org/json_parse.js

var geodata = json_parse("{{geodata|escapejs}}");

I just used escapejs: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs

EDIT: Thanks to Ignacio Vazquez-Abrams. It was him that helped me in #python Freenode. Should have credited him when I made this post. I didn’t know he was in Stackoverflow.

12👍

If you don’t care about old browsers such as IE7, you can simply write:

var geodata = JSON.parse("{{geodata|escapejs}}");

without any extra libraries. See http://caniuse.com/#feat=json for browser versions which support JSON.parse().

I believe the top-voted answer by @adamk has a potential XSS issue. If the JSON contains "</script>", the browser interprets it as the end of <script> tag. So it would be better to use @wenbert ‘s code or mine.

I tried to comment on the answer directly, but I don’t have enough reputation to do that 🙂

2👍

I’ve found that I often want both the object version (for template code) and the JSON version (for JavaScript code), and find it a bit annoying to pass both separately to the template when one should do fine.

If you do want to take the template tag approach and don’t want all the bells and whistles of django argonauts then you can use this template tag which has always done the trick for me. It may not be 100% safe against untrusted data but that’s never been an issue for my use cases.

"""
Usage:

{% import json_tags %}

var = myJsObject = {{ template_var|to_json }};

Features:

- Built in support for dates, datetimes, lazy translations.
- Safe escaping of script tags.
- Support for including QueryDict objects.
- Support for custom serialization methods on objects via defining a `to_json()` method.
"""

import datetime
import json
from decimal import Decimal
from django import template
from django.http import QueryDict
from django.utils.encoding import force_str
from django.utils.functional import Promise
from django.utils.safestring import mark_safe

register = template.Library()

ISO_DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'


def json_handler(obj):
    if callable(getattr(obj, 'to_json', None)):
        return obj.to_json()
    elif isinstance(obj, datetime.datetime):
        return obj.strftime(ISO_DATETIME_FORMAT)
    elif isinstance(obj, datetime.date):
        return obj.isoformat()
    elif isinstance(obj, datetime.time):
        return obj.strftime('%H:%M:%S')
    elif isinstance(obj, Decimal):
        return float(obj)  # warning, potential loss of precision
    elif isinstance(obj, Promise):
        return force_str(obj)  # to support ugettext_lazy
    else:
        return json.JSONEncoder().default(obj)


@register.filter
def to_json(obj):
    def escape_script_tags(unsafe_str):
        # seriously: http://stackoverflow.com/a/1068548/8207
        return unsafe_str.replace('</script>', '<" + "/script>')

    # json.dumps does not properly convert QueryDict array parameter to json
    if isinstance(obj, QueryDict):
        obj = dict(obj)
    return mark_safe(escape_script_tags(json.dumps(obj, default=json_handler)))
👤Cory

1👍

There is a long standing ticket in django about template filter which would output json in templates. The main problem is that it hard to come up with a solution that can be used in different places of html without introducing XSS. For now the following methods can be used.

Store json in html element data attribute:

<div data-geodata="{{json_dump_of_geodata}}"></div>
<script>
  var geodata = JSON.parse(
      document.querySelectorAll('[data-geodata]')[0].getAttribute('data-geodata')
  );
</script>

Or using https://github.com/fusionbox/django-argonauts

<script>
    var geodata = {{geodata|json}};
</script>

Do not use safe filter until you 100% sure that the json doesn’t contain any data from untrusted sources.

UPDATE: In Django 2.1 json_script tag was added as official way to pass json from template context to javascript.

Leave a comment