DJS V14:如何根据参数从JSON中获取指定商品数据
问题
需求:制作Discord斜杠命令/product,传入商品参数(如/product product:"eggs")时,返回该商品的name、price和stock信息。
当前问题:使用for循环遍历JSON数据时,会输出所有商品信息,而非指定商品。
现有JSON数据:
{ "stockItems": [ { "name": "eggs", "price": 50, "stock": 100, "number": 1 }, { "name": "bacon", "price": 70, "stock": 10, "number": 2 }, { "name": "milk", "price": 20, "stock": 250, "number": 3 } ] }
现有代码:
const { readdirSync } = require("fs"); const { EmbedBuilder, SlashCommandBuilder, ApplicationCommandOptionType } = require("discord.js"); const { productInfo } = require("stock.json") module.exports = { data: new SlashCommandBuilder() .setName("product") .setDescription("provides information about different products!") .addStringOption(option => option .setName("product") .setDescription("Type the product you want to view!"), async execute(interaction) { let choice = interaction.options.getString("product") for (let item of productInfo) { let stockInfo = `Name: ${item.name} Price: ${item.price} Stock: ${item.stock}` if (item.number < 4) { console.log(stockInfo) } }
当前控制台输出:
Name: eggs Price: 50 Stock: 100 Name: bacon Price: 70 Stock: 10 Name: milk Price: 20 Stock: 250
询问:如何修改代码,使其仅输出指定商品的信息?
解决方案
需要做三个关键修改,同时优化代码逻辑:
- 修正JSON数据读取路径:你的JSON中商品数组嵌套在
stockItems字段下,需确保正确获取该数组 - 替换循环为精准查找:用
find()方法直接匹配用户指定的商品名称,避免遍历所有商品 - 添加匹配判断与错误反馈:处理商品不存在的情况,避免无输出或报错
修改后的完整代码:
const { EmbedBuilder, SlashCommandBuilder, ApplicationCommandOptionType } = require("discord.js"); // 正确读取JSON文件并提取商品数组 const stockData = require("./stock.json"); const productList = stockData.stockItems; module.exports = { data: new SlashCommandBuilder() .setName("product") .setDescription("provides information about different products!") .addStringOption(option => option .setName("product") .setDescription("Type the product you want to view!") .setRequired(true) // 设为必填,避免用户不传参数 ), async execute(interaction) { // 转小写实现大小写不敏感匹配 const userChoice = interaction.options.getString("product").toLowerCase(); // 查找匹配的商品 const targetProduct = productList.find(item => item.name.toLowerCase() === userChoice); if (targetProduct) { const stockInfo = `Name: ${targetProduct.name} Price: ${targetProduct.price} Stock: ${targetProduct.stock}`; console.log(stockInfo); // 给Discord用户回复结果 await interaction.reply(stockInfo); } else { const notFoundMsg = `Product "${userChoice}" not found in stock`; console.log(notFoundMsg); await interaction.reply(notFoundMsg); } } };
修改说明
find()方法:直接定位到匹配的商品,比for循环更简洁高效- 大小写兼容:将用户输入和商品名称统一转为小写,避免因大小写差异导致匹配失败
- 必填参数:通过
setRequired(true)强制用户传入商品名称,减少无效调用 - 错误处理:找不到商品时输出提示并反馈给用户,提升交互体验
- 路径修正:确保正确读取JSON中的
stockItems数组,解决原代码可能的数据源错误
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

