victor
victor

Reputation: 537

Error getting json using oauthlib python

Im trying to get a pretty json but always have the same error expected string or buffer my code is below

        import urllib2
        import json
        import logging
        from libs.requests_oauthlib import OAuth1Session
        import libs.requests2

        coke = OAuth1Session('user_key',
                             client_secret='user_secret',
                             resource_owner_key='key',
                             resource_owner_secret='key_secret')

        headers = {'content-type': 'application/json'}
        url = "http://test.hdp.pengostores.mx/api/rest/orders"


        response = coke.get(url,headers=headers)
        self.response.out.write(response.text)

My log:

<type 'exceptions.Exception'> (/base/data/home/apps/s~precise-line-76299minutos/devvic.398776853921596377/delivery/handlers.py:5278)
Traceback (most recent call last):
  File "/base/data/home/apps/s~precise-line-76299minutos/devvic.398776853921596377/delivery/handlers.py", line 5274, in get
    response = json.loads(coke.get(url,headers=headers))
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

Upvotes: 1

Views: 63

Answers (1)

furas
furas

Reputation: 142651

In error message you use

json.loads( coke.get(...) )

but get() returns response object - you have to use get().text or get().content (instead of get()) to get text or bytes.

Or try

 data = coke.get(...).json() 

to get directly JSON converted to Python data.


EDIT: to pretty print Python data use pprint.pprint(data) or convert Python data to JSON string using json.dumps()

See example from doc: https://docs.python.org/2/library/json.html

Pretty printing:

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,
...                  indent=4, separators=(',', ': '))
{
    "4": 5,
    "6": 7
}

Upvotes: 2

Related Questions