Python中如何从结果集中获取指定键access_token的值
Python中提取access_token值的方法
根据你的结果集,分两种常见场景处理:
场景1:结果是JSON格式的字符串
如果你的结果集是字符串类型,需要先使用json模块解析成Python字典,再通过键名取值:
import json # 原始JSON字符串 token_result = '{"access_token":"abc","refresh_token":"efg","token_type":"567","scope":78,"expires_in":78}' # 解析为字典 token_dict = json.loads(token_result) # 获取access_token的值 access_token = token_dict['access_token'] print(access_token) # 输出: abc
场景2:结果已经是Python字典
如果你的结果集已经是Python字典对象,直接通过键名access_token取值即可:
# 已转为字典的结果集 token_dict = {"access_token":"abc","refresh_token":"efg","token_type":"567","scope":78,"expires_in":78} # 直接取值 access_token = token_dict['access_token'] print(access_token) # 输出: abc
可选:避免键不存在报错的写法
如果担心access_token键可能不存在,可以用get()方法,指定默认值防止报错:
access_token = token_dict.get('access_token', None) # 若键不存在,access_token会被设为None,不会抛出KeyError
内容的提问来源于stack exchange,提问作者PMP
相关产品推荐
相关产品推荐

