提问者:小点点

节点提取json问题


我目前正在为我的不和谐机器人做一个计算器功能。我做了一个获取steam市场项目价格的命令,然后根据公式进行计算:([price]-[price*0.15])*案例数量,其中0.15是市场费用。问题就出在这里了。程序将json.lowest_price看作一个单词,而不是数字(我认为)。结果,bot发送消息“nan”。我不知道如何使我的代码正确地将json thingy视为一个数字。请帮助<3。这是我的代码:

const Discord = require('discord.js');
const fetch = require('node-fetch');
const client = new Discord.Client();

client.login('[TOKEN]');
 

client.on('ready', () => {
  console.log(`Logged in as TEST`);
});


//////////////////////////////////

const prefix = "!";
client.on('message', message =>{
  if (!message.content.startsWith(prefix) || message.author.bot) return;
  const args = message.content.slice(prefix.length).trim().split(/ +/);
  const command = args.shift().toLowerCase();

if (command === 'calculate') {
  if (!args.length){
    return message.channel.send(`Invalid argument`);
  } else if (args[0] === 'breakout'){
    fetch(
    'https://steamcommunity.com/market/priceoverview/?appid=730&market_hash_name=Operation%20Breakout%20Weapon%20Case&currency=6',
  )
    .then((res) => res.json())
    .then((json) =>
      message.channel.send(
        `From ${args[1]] breakout cases you will get ${((json.lowest_price)-((json.lowest_price)*0.15))*(args[1])}`,
      ),
    )
    .catch((error) => {
      console.log(error);
      message.channel.send('tracking breakout price failed');
    });
  }

}

});


共1个答案

匿名用户

似乎API确实在lowest_price字段中包含了货币,这就是为什么使用它时会收到NaN。

您可以手动将其转换为一个数字,但我建议您安装currency.js包,因为使用它确实很容易。它可以从任何货币获得价值,并有内置的乘法,和你需要的减法。查看下面的工作代码:

const currency = require('currency.js');

// ... 
// ...


client.on('message', (message) => {
  if (!message.content.startsWith(prefix) || message.author.bot) return;
  const args = message.content.slice(prefix.length).trim().split(/ +/);
  const command = args.shift().toLowerCase();

  // you can change the format, localising the decimal and/or delimiter
  const zloty = (value) =>
    currency(value, { symbol: 'zł', separator: '.', decimal: ',' });

  if (command === 'calculate') {
    if (!args.length) {
      return message.channel.send(`Invalid argument`);
    } else if (args[0] === 'breakout') {
      fetch(
        'https://steamcommunity.com/market/priceoverview/?appid=730&market_hash_name=Operation%20Breakout%20Weapon%20Case&currency=6'
      )
        .then((res) => res.json())
        .then((json) => {
          // calculate the final price using currency.js only
          const finalPrice = zloty(
            zloty(json.lowest_price)
             .subtract(
               zloty(json.lowest_price)
                 .multiply(0.15)
               )
            )
            .multiply(args[1])
            .format();

          message.channel.send(`From ${args[1]} breakout cases you will get ${finalPrice}`);
        })
        .catch((error) => {
          console.log(error);
          message.channel.send('tracking breakout price failed');
        });
    }
  }
});