簡體   English   中英

如何正確格式化來自背包.tf API 請求的 JSON 數據?

[英]How can I correctly format this JSON data from a backpack.tf API request?

我正在嘗試使用我正在開發的 Discord Bot 的背包.tf API。 我目前正在嘗試它的UserInfo部分。 在 API URL 中使用我自己的 Steam ID 會導致此 output 在此處輸入圖像描述

本質上,有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"]
}

其中大部分只是框架,但它基本上是通過超級代理調用 API。 當它返回時,我嘗試使用body.users.id.avatar來獲取用戶的頭像。 它不這樣做,而是輸出UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'avatar' of undefined error。 API 在它只是body.users.id時似乎沒有給出任何錯誤,但是向它添加另一層會提示它中斷。

我希望它只是給我我想要的結果。 謝謝。

看起來您正在嘗試使用動態屬性名稱, body.users是 object,其鍵值是帶有數字的實際 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 })

這條線可能會給出錯誤,無論哪種方式,它都不會是錯誤的,因為它評估 object 是否真實,無論屬性如何

如果您嘗試對此進行錯誤處理,則它需要在代碼中更早,並且您需要使用.catch代替,除非 API 即使 ID 無效也不會引發錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM