Python 中的字符串到字典 [英] String to Dictionary in Python

查看:23
本文介绍了Python 中的字符串到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在这上面花了很多时间,在我看来这应该是一个简单的修复.我正在尝试使用 Facebook 的身份验证在我的网站上注册用户,我正在尝试在服务器端进行.我已经到了获得访问令牌的地步,当我去:

So I've spent way to much time on this, and it seems to me like it should be a simple fix. I'm trying to use Facebook's Authentication to register users on my site, and I'm trying to do it server side. I've gotten to the point where I get my access token, and when I go to:

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

我得到的信息是这样的字符串:

I get the information I'm looking for as a string that's like this:

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

似乎我应该能够在此使用 dict(string) 但我收到此错误:

It seems like I should just be able to use dict(string) on this but I'm getting this error:

ValueError: 字典更新序列元素 #0 的长度为 1;2 是必需的

所以我尝试使用 Pickle,但出现此错误:

So I tried using Pickle, but got this error:

KeyError: '{'

我尝试使用 django.serializers 对其进行反序列化,但结果相似.有什么想法吗?我觉得答案必须很简单,而我只是愚蠢.感谢您的帮助!

I tried using django.serializers to de-serialize it but had similar results. Any thoughts? I feel like the answer has to be simple, and I'm just being stupid. Thanks for any help!

推荐答案

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

This data is JSON! You can deserialize it using the built-in json module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson module.

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

这篇关于Python 中的字符串到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆