Python中将字符串转换为字典

183 投票
3 回答
293628 浏览
提问于 2025-04-16 11:21

我花了太多时间在这个问题上,感觉应该是个简单的解决办法。我想在我的网站上使用Facebook的认证来注册用户,而且是想在服务器端进行操作。我已经拿到了我的访问令牌,当我访问这个链接:

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

我得到了我想要的信息,内容是这样的一个字符串:

{"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

于是我尝试用Pickle,但又出现了这个错误:

KeyError: '{'

我还尝试使用 django.serializers 来反序列化,但结果也差不多。有没有什么想法?我感觉答案应该很简单,我就是搞不懂。谢谢任何帮助!

3 个回答

1

在Python 3.x中

import json
t_string = '{"Prajot" : 1, "Kuvalekar" : 3}'
res = json.loads(t_string)
print(res) # <dict>  {"Prajot" : 1, "Kuvalekar" : 3}
24

使用 ast.literal_eval 来处理 Python 的基本数据类型。不过,你现在处理的是 JSON 格式的数据(比如里面的 "true"),所以应该用 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'}
335

这些数据是 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

撰写回答