4

I need a clarification. If I for example do a view with a serialized object:

def sample(request):
    res = [{'name':'man'}]
    encoded = json.dumps(res)
    return render_to_response('sample/example.html',{'encoded':encoded} )

In my templates I pass:

{{encoded}}

Now from a python script can I do:

data = json.loads(urllib2.urlopen(url/to/site).read()

It says ValueError: No JSON object could be decoded. But isn't {{encoded}} a json object? And if so how would I get it?

Thank you

2
  • 3
    I'd do a print urllib2.urlopen(url/to/site).read() first. I'm betting that Django escapes the string. Commented Feb 9, 2012 at 16:24
  • That's an escaped HTML string. " should be a '. See my answer. Commented Feb 9, 2012 at 16:31

2 Answers 2

9

Try this in your template:

{% autoescape off %} 
  {{ encoded }}
{% endautoescape %} 
Sign up to request clarification or add additional context in comments.

2 Comments

I get [{"name": "man"}] using autoescape in print urllib2.urlopen but still can't decode the json object. Thank you very much.
Is there anything else besides that text in the page? Any HTML code?
1

You will probably find that there are quote marks getting escaped by Django. I had a similar problem with a Jinja2 template recently. In my case, the JSON was going into an HTML data attribute and was escaping things improperly. After I used a filter to mark it safe, it stopped escaping the quote marks and there were mismatched quotes. The solution was

{% set dbl_quote='"' %}
{{ encoded |replace(dbl_quote, '"') |safe}}

but that will probably look different in Django.

You may need to use {% autoescape off %} or something similar instead if you're templating it straight into Javascript, etc.

1 Comment

And whatever you do, you might want to do something like this snippet to convert to JSON in a filter so if you have to mark it safe or whatever you can do that in one place inside the filter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.