string到Python中的字典

所以我花了很多时间在这方面,在我看来这应该是一个简单的修复。 我正在尝试使用Facebook的身份validation在我的网站上注册用户,我试图做服务器端。 我已经到了获取我的访问令牌的地步,而当我到达时:

https://graph.facebook.com/me?access_token=MY_ACCESS_TOKEN

我得到的信息,我正在寻找一个string,就像这样:

{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}

似乎我应该只能使用dict(string) ,但我得到这个错误:

ValueError: dictionary update sequence element #0 has length 1; 2 is required

所以我尝试使用腌菜,但得到这个错误:

KeyError: '{'

我尝试使用django.serializers去序列化,但有类似的结果。 有什么想法吗? 我觉得答案很简单,我只是愚蠢的。 谢谢你的帮助!

这个数据是JSON ! 如果你使用Python 2.6+,你可以使用内置的json模块来反序列化它,否则你可以使用优秀的第三方simplejson模块 。

 import json # or `import simplejson as json` if on Python < 2.6 json_string = u'{ "id":"123456789", ... }' obj = json.loads(json_string) # obj now contains a dict of the data 

使用ast.literal_eval来评估Python文字。 然而,你有什么是JSON(例如注意“真”),所以使用JSON解串器。

 >>> import json >>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}""" >>> json.loads(s) {u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'jdoe@gmail.com', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}