python的requests接口测试中,requests.get(url, url_params).text返回的看起来像个字典,使用dict[key]却取不到value,报错:TypeError: string indices must be integers。
代码如下,url是公司项目,不便显示:
url ='XXX'
url_params = {'isCanceled':2, 'cellphone':'18628320001'}
r = requests.get(url, url_params)
b = r.text
print(b)
print(b['errcode'])
出现如下提示:

单独打印b的内容,看起来是个字典。

print(type(b))发现是个str。
需要使用json.loads(b)转为字典。
加上代码:
b = json.loads(b)
print(type(b)),b已经转为dict,可以使用key查到对应的value。
网友评论