Reputation: 7110
I'm passing a JSON String from the server to a Django template. When I assign the JSON String to a jQuery variable, I'm getting unicode syntax.
Py:
# Call Facebook Graph API to get list of Friends.
result = facebook.GraphAPI(
user.access_token).get_connections('me', 'friends')
friends = result["data"]
jQuery/Django template:
var friends = {{friends}};
Inspecting the assignment in Firebug:
[
{
u'name': u'Joe Smith',
u'id': u'6500000'
},
{
u'name': u'Andrew Smith',
u'id': u'82000'
},
{
u'name': u'Dora Smith',
u'id': u'97000000'
}
]
Upvotes: 1
Views: 1900
Reputation: 44192
As Brian Goldman points out, the friends
variable isn't a JSON string, like you say, but a Python object, which looks enough like JSON when printed out to pass for it, sometimes.
You need to convert it to proper JSON before passing it to the template. At the top of your views.py
, put this line
from django.utils import simplejson
And then pass simplejson.dumps(friends)
to the template, rather than just friends
.
Whatever you do, just don't try to construct the JSON by hand in the template :) If you don't fully control the source data (and you don't; in this case it comes from Facebook) you will have no end of troubles with your template.
Upvotes: 2
Reputation: 736
You need to convert friends
to JSON on the server side. You're seeing the Python representation, which looks like kind of like JSON sometimes but isn't.
Upvotes: 4
Reputation: 34718
When python represents a string, u'123'
for example then it means the string is unicode, there would be no real advantage to escaping this or removing it, it still behaves like a normal string
Upvotes: 1