简体   繁体   English

如何在JSON字符串中转义unicode语法(u'foo')?

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

I'm passing a JSON String from the server to a Django template. 我正在将JSON字符串从服务器传递到Django模板。 When I assign the JSON String to a jQuery variable, I'm getting unicode syntax. 当我将JSON字符串分配给jQuery变量时,我正在获得unicode语法。

Py: 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: jQuery / Django模板:

var friends = {{friends}};

Inspecting the assignment in Firebug: 在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. 您需要在服务器端将friends转换为JSON。 You're seeing the Python representation, which looks like kind of like JSON sometimes but isn't. 您会看到Python表示形式,有时看起来像JSON,但实际上不是。

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. 正如布莱恩·戈德曼(Brian Goldman)所指出的,正如您所说的, friends变量不是JSON字符串,而是Python对象,有时在打印输出时看起来像JSON。

You need to convert it to proper JSON before passing it to the template. 您需要先将其转换为适当的JSON,然后再将其传递给模板。 At the top of your views.py , put this line 在您views.py的顶部,将这一行

from django.utils import simplejson

And then pass simplejson.dumps(friends) to the template, rather than just friends . 然后将simplejson.dumps(friends)传递给模板,而不是仅将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. 无论您做什么,都不要尝试在模板中手动构造JSON :)如果您无法完全控制源数据(并且您没有,在这种情况下,它来自Facebook),您将无穷无尽。模板的麻烦。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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