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

如何在Node.js Telegram Bot中正确显示对象,避免[object object]

Node.js Telegram Bot 正确展示对象内容的解决方法

当你直接在模板字符串中插入对象 _coinList 时,JavaScript 会默认调用对象的 toString() 方法,返回 [object Object],这就是你看到该内容的原因。以下是几种正确展示对象内容的方式:

  • 方式一:将对象转为 JSON 字符串
    使用 JSON.stringify() 把对象转为可读的字符串格式,添加缩进还能让结构更清晰:

    await bot.sendMessage(chat_id, `The current price of ${JSON.stringify(_coinList, null, 2)}.`);
    

    注意:如果对象包含循环引用,这个方法会报错,需要提前处理。

  • 方式二:提取对象的特定属性
    如果你只需要对象中的部分信息,直接提取对应字段即可,比如假设 _coinList 包含 name 和 price 属性:

    await bot.sendMessage(chat_id, `The current price of ${_coinList.name} is ${_coinList.price}.`);
    
  • 方式三:自定义对象的 toString 方法
    给对象的类添加自定义的 toString() 方法,让它返回你需要的格式:

    // 假设 _coinList 是 Coin 类的实例
    class Coin {
      constructor(name, price) {
        this.name = name;
        this.price = price;
      }
      toString() {
        return `${this.name}: ${this.price}`;
      }
    }
    // 发送消息时直接使用对象
    await bot.sendMessage(chat_id, `The current price of ${_coinList}.`);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:51:32