【问题标题】:How can I correctly format this JSON data from a backpack.tf API request?如何正确格式化来自背包.tf API 请求的 JSON 数据?
【发布时间】:2020-10-17 13:10:03
【问题描述】:

我正在尝试将backpack.tf API 用于我正在开发的 Discord Bot。我目前正在尝试其中的UserInfo 部分。在 API URL 中使用我自己的 Steam ID 会导致此输出

基本上,有users,然后是ID,最后是我尝试使用的实际信息。我的代码如下:

const Discord = require("discord.js");
const superagent = require("superagent");
const { apiKey } = require("../db/config.json");
module.exports = {
    run: async(client, message, args) => {
        if (!args[0]) return message.channel.send("Enter in a steam ID!")
        let id = args[0]
        console.log(id)
        let { body } = await superagent
            .get(`https://backpack.tf/api/users/info/v1?steamids=${id}&key=${apiKey}`);
        message.channel.send(
            new Discord.MessageEmbed()
            .setImage(body.users.id.avatar)
        );
        if (!{ body }) return message.channel.send("Check that ID again!");
    },
    aliases: ["bp"]
}

其中大部分只是框架,但它基本上是通过 superagent 调用 API。当它返回时,我尝试使用body.users.id.avatar 来获取用户的头像。它没有这样做,而是输出UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'avatar' of undefined 错误。当它只是body.users.id 时,API 似乎没有给出任何错误,但是向它添加另一个层会提示它中断。

我希望它简单地给我我要求的结果。谢谢。

【问题讨论】:

    标签: javascript node.js json discord discord.js


    【解决方案1】:

    看起来您正在尝试使用动态属性名称,body.users 是一个对象,其键值是带有数字的实际 id,不会有直接的 .id 属性,因此 body.users.id 未定义

    body.users.id 没有给出任何错误的原因是因为它只是未定义,但您并没有尝试调用它的属性,就像您调用 body.users.id.avatar 时所做的那样

    body.users.id.avatar => undefined.avatar

    这应该可以解决它:

    body.users[id].avatar
    

    外观示例:

    const id = "2324389";
    const obj = {
      "2324389": 23,
      "1234678": 22,
      "id": 21
    };
    
    obj.id
    // => 21
    
    obj[id]
    // => 23
    
    /* obj[id] is the same as below */
    
    obj["2324389"]
    // => 23
    
    

    还有:if (!{ body })

    这行可能会给出错误,无论哪种方式,它都不会是假的,因为它会评估对象是否真实,而不管属性如何

    如果您尝试对此进行错误处理,则它需要在代码中较早,并且您需要改用.catch,除非即使 ID 无效,API 也不会抛出错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多