You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用RapidAPI返回JSON字符串后索引报错,如何提取email和timestamp?

解决TypeError:字符串索引必须为整数的问题

问题原因

你当前的response是字符串类型(因为调用了.text方法),而非Python字典。字符串只能用整数索引访问,所以尝试用response['items']会触发TypeError。

两种解决方法

方法1:使用requests内置的.json()直接解析

requests库提供了.json()方法,可以直接将JSON格式的响应内容解析为Python字典,无需手动处理字符串:

import requests

url = "**************"
querystring = {"domain":"gmail.com","username":"random","server":"server-1","type":"real"}
headers = {
    "X-RapidAPI-Key": "******************",
    "X-RapidAPI-Host": "*****************"
}

# 直接解析为字典,替换原来的.text
response_dict = requests.request("GET", url, headers=headers, params=querystring).json()

# 提取email和timestamp到变量
email = response_dict['items']['email']
timestamp = response_dict['items']['timestamp']

# 验证结果
print(email)  # 输出: vinhvivyanvinh72943@gmail.com
print(timestamp)  # 输出: 1659215390

方法2:用json模块手动解析字符串

如果已经获取了字符串格式的响应,可以导入json模块将其转为字典:

import requests
import json

url = "**************"
querystring = {"domain":"gmail.com","username":"random","server":"server-1","type":"real"}
headers = {
    "X-RapidAPI-Key": "******************",
    "X-RapidAPI-Host": "*****************"
}

# 先获取字符串响应
response_str = requests.request("GET", url, headers=headers, params=querystring).text
# 转为字典
response_dict = json.loads(response_str)

# 提取数据
email = response_dict['items']['email']
timestamp = response_dict['items']['timestamp']

内容的提问来源于stack exchange,提问作者eymentakak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:54:51