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

如何过滤拉取到的JSON数据?Imgur接口筛选animated字段返回空数组排查

问题原因与修复方案

核心错误原因

你写的筛选条件存在类型不匹配问题:
接口返回的animated字段是布尔类型,有效值为true/false,但你在判断时用了字符串"false"做对比。在JavaScript中,false == "false"的判定结果为false,所以筛选条件永远无法命中符合要求的静态图,最终返回空数组。

另外还有两处需要修正的细节:

  • Array.filter是同步方法,调用时不需要加await关键字
  • 你当前随机选图时仍在使用未筛选的原始data数组,即使筛选逻辑修正,也还是可能抽到动图,需要改为从筛选后的filtered数组中选取

修正后的代码

async execute(interaction) {
  const data = await fetch(
    `https://imgur.com/r/${
      subreddits[Math.floor(Math.random() * subreddits.length)]
    }/hot.json`
  )
    .then((response) => response.json())
    .then((body) => body.data)

  // 修正筛选条件:直接对比布尔值false,去掉多余await
  const filtered = data.filter(
    (element) => element.animated === false
  );
  console.log(filtered);
  // 从筛选后的数组随机选图
  const selected = filtered[Math.floor(Math.random() * filtered.length)];
  await interaction.reply({
    content: `https://imgur.com/${selected.hash}${selected.ext.replace(
      /\?.*/,
      ""
    )}`,
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:27:03