javascript - axios get请求后访问json数据
问题描述
我一直在尝试制作一个与 Shoppy API ( https://shoppy.dev/ ) 一起使用的 Discord Bot。我对 Javascript 完全陌生——但对编码并不陌生!
我对 Axios 进行了一些研究,并设法使用它从 Shoppy 帐户中提取订单列表。问题是,有大量数据我只想向用户显示其中的一部分。我不得不在下面的代码中编辑一些信息,但这就是我所拥有的:
case 'orders':
async function makeRequest() {
const config = {
method: 'get',
url: 'https://shoppy.gg/api/v1/orders/',
headers: {
'Authorization': 'REDACTED - MY API KEY',
'Content-Type': 'application/json',
'Connection': 'keep-alive'
}
}
axios(config)
.then(response => {
console.log(response.data);
});
}
makeRequest();
break;
这会在控制台中产生以下输出。我在这里仅列出了一些信息只是为了显示格式,但您大致了解:
Bot Online
[
{
id: 'REDACTED',
pay_id: null,
product_id: 'REDACTED',
coupon_id: null,
price: 3,
currency: 'CAD',
exchange_rate: null,
email: 'REDACTED',
delivered: 1,
confirmations: 1,
required_confirmations: 1,
我的问题是 - 例如,我无法弄清楚如何从“电子邮件”中获取数据并将其显示给用户。我花了几个小时尝试不同的方式,但控制台总是只显示“未定义”。
我觉得这是一件超级简单的事情,我只是没有得到任何东西。有人有建议吗?为了给这段代码提供更多的上下文,用户正在编写“!订单”,机器人将用他们的订单列表进行响应——但我只希望机器人显示类似“订单 ID”、“产品名称”之类的内容, '电子邮件'。所以我不需要所有被提取的数据。
谢谢!!
解决方案
请求返回一个数组。因此,您需要对其进行迭代以获取所有元素。您可以在响应回调中使用 for 循环或 map 函数来执行此操作。
axios(config).then(response => {
console.log(response.data);
//Add the for loop or the map operator here
})
要使用 for 循环:
for(let x of response.data){
//x gives you an individual item. Do whatever you want with it.
// x.email gives you the email
}
要使用地图运算符:
var emails = response.data.map(x => {
return x.email;
});
//emails contains the array of all emails
您可以在 for 循环或地图运算符中添加自己的验证以选择适当的电子邮件...
推荐阅读
- docker - 给 docker 容器写权限
- sql - 比较两个表并获取记录新旧值
- .net - 使用 Json.NET 为 F# 记录标签填充复杂的默认值
- ubuntu - 重新安装后 npm 找不到模块“semver”
- html - 如何实现横向卡片样式
- sql - 通过sql过程从另一个表和新值插入sql表
- reactjs - 使用 HoC 时如何正确分配通用道具?
- python - 当前路径具有子目录或 url 参数时,使用 AJAX 调用视图函数不起作用(Django)
- html - 如何以角度明智地制作组件视图的加载器
- javascript - 如果我有两个共享域的 iframe,一个上的 postmessage 会触发另一个上的消息事件吗?