如何从 python 中的 json 字典中获取值?
How to get a value from json dictionary in python?
运行 我的代码的结果是这样的:
b'{"username":"test","available":false,"status":"unavailable","failed_reason":null,"callback_url":"http://www.twitter.com/"}'
我怎样才能真正从这个响应中得到 [username] 的值?
使用 json
模块将您的数据转换为 json,然后使用 get
进行简单访问。使用您的数据结构观察下面的演示:
Python 2 方法
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 方法
您在 Python 3 中必须小心,因为 json 需要一个字符串,因此对于您的特定情况,您需要解码 utf-8
。所以这个例子在 Python 3 中是这样工作的:
>>> 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'
这是 Python 2 条关于 json
的信息
这是 Python 3 条关于 json
的信息
因为是字节串,所以先解码即可
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'])
运行 我的代码的结果是这样的:
b'{"username":"test","available":false,"status":"unavailable","failed_reason":null,"callback_url":"http://www.twitter.com/"}'
我怎样才能真正从这个响应中得到 [username] 的值?
使用 json
模块将您的数据转换为 json,然后使用 get
进行简单访问。使用您的数据结构观察下面的演示:
Python 2 方法
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 方法
您在 Python 3 中必须小心,因为 json 需要一个字符串,因此对于您的特定情况,您需要解码 utf-8
。所以这个例子在 Python 3 中是这样工作的:
>>> 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'
这是 Python 2 条关于 json
的信息这是 Python 3 条关于 json
的信息因为是字节串,所以先解码即可
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'])