Lucas Ou-Yang
Lucas Ou-Yang

Reputation: 5655

Issues with json strings and django templates

I am trying to query a list of data, convert it into a json object, and pass it into my javascript so it can be evaluated there:

var data = '{{ passed_list|jsonify }}';

# This evaluates to:

var news = '[{"pk": 133, "model": "Article.article
    ","fields":

However, this wont work because I am trying to access elements.

For example,

var object = data[0].pk;
In my view source, this does not evaluate to 133 as expected but it evaluates
to ... data[0].pk ... which is a bit confusing.

Here is my jsonify:

 if isinstance(object, QuerySet):
    return serialize('json', object)
return simplejson.dumps(object, ensure_ascii=False)

Any help would be appreciated, thanks.

Upvotes: 2

Views: 665

Answers (2)

kszl
kszl

Reputation: 1213

var data = '{{ portfolio|jsonify|escapejs|safe }}';

Filter escapejs put after jsonify solves the problem with special characters like: '

Upvotes: 0

second
second

Reputation: 28637

django will escape html characters by default

if you completely trust the data, (i.e. it comes from your code, and no part of the content could come from a user), you can use

var data = '{{ passed_list|jsonify|safe }}';

to tell django not to escape it

Upvotes: 1

Related Questions