Python datastructures into js datastructures using jinja2 template (lists and dicts)
Question: I have a very similar problem to this question, [Python datastructures into js
datastructures using Django templates (lists and
dicts)](http://stackoverflow.com/questions/9547185/python-datastructures-into-
js-datastructures-using-django-templates-lists-and-d) but with the next step -
how do the variable names in python that are strings become javascript
objects?

So in python I have this:

    
    
    data = [{'year': 2006, 'books': 54, 'author': 'fred'},
        {'year': 2007, 'books': 43, 'author': 'sue'},
        {'year': 2008, 'books': 41, 'author': 'bill'},
        {'year': 2009, 'books': 44, 'author': 'alex'},
        {'year': 2010, 'books': 35, 'author': 'fred'}]
    

which I can output into my javascript via {{ data | safe }}

but I would like my javascript to look like this:

    
    
    var data = [{year: 2006, books: 54, author: 'fred'},
        {year: 2007, books: 43, author: 'sue'},
        {year: 2008, books: 41, author: 'bill'},
        {year: 2009, books: 44, author: 'alex'},
        {year: 2010, books: 35, author: 'fred'}];
    

whereas it comes out at the moment like this:

    
    
    var data = [{'year': 2006, 'books': 54, 'author': 'fred'},
        {'year': 2007, 'books': 43, 'author': 'sue'},
        {'year': 2008, 'books': 41, 'author': 'bill'},
        {'year': 2009, 'books': 44, 'author': 'alex'},
        {'year': 2010, 'books': 35, 'author': 'fred'}];
    

Is there anyway to do this?

Many thanks, Mark


Answer: The [`tojson`
filter](https://flask.readthedocs.org/en/latest/templating/#standard-filters)
included with Flask takes care of producing a valid Javascript subset that is
also HTML safe:

    
    
    var data = {{ data|tojson|safe }};
    

If you are not using Flask, then [register a custom
filter](http://jinja.pocoo.org/docs/api/#writing-filters) like:

    
    
    import json
    
    def tojson(obj):
        """Produce HTML-safe JSON"""
        return (json.dumps(obj)
                    .replace(u'<', u'\\u003c')
                    .replace(u'>', u'\\u003e')
                    .replace(u'&', u'\\u0026')
                    .replace(u"'", u'\\u0027'))
    

