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 ?
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 ?
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:
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'
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
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'])