0

The result of running my code is something like:

b'{"username":"test","available":false,"status":"unavailable","failed_reason":null,"callback_url":"http://www.twitter.com/"}'

How can I actually get the value of [username] from this response ?

Steve
  • 722
  • 4
  • 10
  • 24

2 Answers2

3

Use the json module to convert your data to json and then it's a simple access with get after that. Observe the demo below with your data structure:

Python 2 approach

In [5]: import json

In [6]: a = json.loads(b'{"username":"test","available":false,"status":"unavailable","failed_reason":null,"callback_url":"http://www.twitter.com/"}')

In [7]: a
Out[7]:
{u'available': False,
 u'callback_url': u'http://www.twitter.com/',
 u'failed_reason': None,
 u'status': u'unavailable',
 u'username': u'test'}

In [8]: a.get('username')
Out[8]: u'test'

Python 3 Approach

You have to be careful in Python 3 as json expects a string, therefore for your particular case you need to decode utf-8. So this example works in Python 3 as such:

>>> a = b'{"username":"test","available":false,"status":"unavailable","failed_reason":null,"callback_url":"http://www.twitter.com/"}'
>>> a = a.decode('utf-8')
>>> import json
>>> a = json.loads(a)
>>> a.get('username')
'test'

Here is Python 2 information on json

Here is Python 3 information on json

idjaw
  • 25,487
  • 7
  • 64
  • 83
0

Since it is a byte string, you just have to decode it first.

import json

data = b'{"username":"test","available":false,"status":"unavailable","failed_reason":null,"callback_url":"http://www.twitter.com/"}'
a = json.loads(data.decode('utf-8'))
print(a['username'])
wags
  • 149
  • 12