简体   繁体   中英

How to escape unicode syntax (u'foo') in JSON string?

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'
      }
]

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.

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.

当python代表一个字符串,例如u'123' ,则意味着该字符串是unicode,转义或删除它并没有任何真正的优势,它的行为仍与普通字符串相似

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM