V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
MagaFun
V2EX  ›  Python

利用 requests 库请求 Instagram 的 API 返回的是字符串,怎样转换成字典?

  •  
  •   MagaFun · 2017-09-21 06:13:28 +08:00 · 2413 次点击
    这是一个创建于 2409 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近在做一些 Instagram 相关的项目,Python 上并没有可靠的 Instagram API,所以决定直接使用 requests 库。以下为代码段:

    def getMe():
        while True:
            mediaMe = requests.get('https://api.instagram.com/v1/users/self/media/recent/?access_token={0}&count=1'.format(access_token))
            print mediaMe.content
            print type(mediaMe.content)
            yield ast.literal_eval(mediaMe.content)
    
    with open('instagram.log', 'a') as log:
        getMe()
        for line in getMe():
            log.write(json.dumps(line))
            log.write('\n')
           
            print type(line)
    

    然后问题出现了,mediaMe 返回的是一个类,mediaMe.content 返回的类型是一个字符串,这个字符串是被字符化的一个词典。尝试使用 ast.literal_eval(mediaMe.content) 转换为词典的时候,却提示 Malformed string。请问有什么解决的方法吗?先提前谢谢大家。

    7 条回复    2017-09-22 20:10:52 +08:00
    Cooky
        1
    Cooky  
       2017-09-21 06:38:21 +08:00 via Android
    json.loads
    janxin
        2
    janxin  
       2017-09-21 07:13:34 +08:00 via iPad   ❤️ 1
    mediaMe.json()
    iyaozhen
        3
    iyaozhen  
       2017-09-21 08:23:51 +08:00 via Android
    你这代码写的有点看不懂呀。
    getMe 是个死循环?
    然后 getMe 是个迭代生成器,但遍历这个迭代器的之前又调用了下?
    mec
        4
    mec  
       2017-09-21 10:05:46 +08:00
    response 对象不是有个 json 方法吗?
    timonwong
        5
    timonwong  
       2017-09-21 11:01:44 +08:00
    1. response 有个 json() 方法
    2. response 的 json() 方法调用 text 属性
    3. text 属性,如果 response 没有 Content-Encoding 会执行一次巨慢的 chardet
    4. 因此在调用 text/json() 之前,请 response.encoding = 'utf-8' ( instagram 的 API 不返回 Content-Encoding 头)
    timonwong
        6
    timonwong  
       2017-09-21 11:23:10 +08:00
    我纠正一下上面的第 4 点,Content-Type 里面有 charset 了,不用强设
    MagaFun
        7
    MagaFun  
    OP
       2017-09-22 20:10:52 +08:00
    @janxin 问题是 mediaMe 返回的是一个 Response 200,必须要用 mediaMe.content 才能解出数据来
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3143 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:04 · PVG 08:04 · LAX 17:04 · JFK 20:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.