TypeScript中如何用Axios提取JSON响应的token.symbol与Name字段
提取GMGN API响应中的token字段数据
你当前的代码仅打印了完整响应对象,要获取目标字段,需要逐层访问响应的嵌套结构,直接提取res.data.data.token下的symbol和name(注意字段名大小写需与API返回一致,若响应中是Name则对应tokenData.Name)。
修改后的代码(JavaScript版本)
const axios = require('axios') axios.get('https://gmgn.ai/defi/quotation/v1/tokens/sol/EV1k3kQwueeD3uYr3wMzeydYc94qqrpjfHdCNVs2A22d') .then(res => { // 定位到目标token对象 const tokenData = res.data.data.token; // 提取所需字段 const tokenSymbol = tokenData.symbol; const tokenName = tokenData.name; // 若响应中字段名为Name则改为tokenData.Name console.log('代币符号:', tokenSymbol); console.log('代币名称:', tokenName); }) .catch(err => { // 新增错误处理,排查请求失败问题 console.error('请求失败:', err); });
TypeScript版本(带类型约束)
如果你使用TypeScript,建议定义接口来约束响应结构,避免类型报错:
import axios from 'axios'; // 定义API响应的类型结构 interface GMGNTokenResponse { data: { token: { symbol: string; name: string; // 字段名需与实际响应匹配,若为Name则改为Name: string }; }; } axios.get<GMGNTokenResponse>('https://gmgn.ai/defi/quotation/v1/tokens/sol/EV1k3kQwueeD3uYr3wMzeydYc94qqrpjfHdCNVs2A22d') .then(res => { const tokenData = res.data.data.token; console.log('代币符号:', tokenData.symbol); console.log('代币名称:', tokenData.name); }) .catch(err => { console.error('请求失败:', err); });
说明
- 核心逻辑是通过
res.data.data.token逐层访问嵌套对象,API响应的结构是外层res.data包含一个data属性,其下才是token对象 - 增加
catch块可以捕获请求过程中的错误(如网络异常、API返回错误状态码等),方便排查问题 - 若运行时报错
Cannot read properties of undefined,说明响应结构与预期不符,可先打印res.data确认实际返回的字段名和层级
内容的提问来源于stack exchange,提问作者Paul tje
相关产品推荐
相关产品推荐

