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

读取Coinbase API返回数据时遇TypeError:string indices must be integers

解决Coinbase API响应访问字段时的TypeError问题

错误原因

你实际拿到的json_response是字符串类型,而非Python字典。虽然你贴出的内容是字典格式,但Coinbase API返回的原始数据本质是JSON字符串,直接对字符串使用["ask"]这种字典索引方式,就会触发TypeError: string indices must be integers错误。

解决方法

方法1:手动解析JSON字符串

使用Python内置的json模块,把JSON格式的字符串转换成字典:

import json

# 替换为你从API获取到的原始字符串响应
raw_response = '{"ask":"19540.18","bid":"19538.23","volume":"46199.99613583","trade_id":420452773,"price":"19539.07","size":"0.00091338","time":"2022-09-28T16:44:27.381482Z"}'

# 将字符串解析为字典
json_response = json.loads(raw_response)

# 现在可以正常访问字段
print(json_response["ask"])

方法2:用requests库自动解析(推荐)

如果是通过requests库调用API,直接使用response.json()方法就能自动把响应转换成字典:

import requests

# 替换为你的Coinbase API接口地址
api_url = "你的Coinbase API接口URL"
response = requests.get(api_url)

# 自动解析为字典
json_response = response.json()

# 访问目标字段(若API响应有嵌套结构,需根据实际调整路径)
print(json_response["ask"])

验证方法

解析完成后,执行print(type(json_response)),返回<class 'dict'>就说明转换成功,此时使用键索引就不会报错了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:11:40