Javascript 如何使用NodeJS循环浏览JSON文件

Javascript 如何使用NodeJS循环浏览JSON文件,javascript,node.js,discord.js,Javascript,Node.js,Discord.js,我正在开发一个Discord机器人,为高级成员提供命令 bullers.json: buyers.json: { “买方”:[ { “id”:“331499609509724162” }, { “id”:“181336616164392960” }, { “id”:“266389854122672128” } ] }您正在将uID(我假定是字符串)与数组中的每个对象(包含字符串)进行比较 尝试比较买家对象的id属性: if (uID === ftpr.buyers[i].id) { } 确保

我正在开发一个Discord机器人,为高级成员提供命令

bullers.json:

buyers.json:
{
“买方”:[
{
“id”:“331499609509724162”
},
{
“id”:“181336616164392960”
},
{
“id”:“266389854122672128”
}
]
}
您正在将uID(我假定是字符串)与数组中的每个对象(包含字符串)进行比较

尝试比较买家对象的id属性:

if (uID === ftpr.buyers[i].id) { }

确保
message.author.id
和ftpr.buyers id的类型相同,
ftpr.buyers
是包含字符串id的对象数组。您应该通过执行console.log(type of message.author.id,message.author.id)

您可以通过在切换案例之前使用包含id的字符串数组来简化代码:

const ids = ftpr.buyers.map(b = b.id);//this is now ["331499609509724162",...]

  case "spotify":
      if (ids.includes(message.author.id)) {
        var _embed = new Discord.RichEmbed()
          .setTitle("Spotify")
          .addField("Username", "testsda@yahoo.com")
          .addField("Password", "ithastobe8")
          .setColor(0x00FFFF)
          .setFooter("Sincerely, LajgaardMoneyService")
          .setThumbnail(message.author.avatarURL);
        message.author.send(_embed);
        console.log(message.author + " Just used the command !spotify")
      }

    break;

您实际上是在导出对象,还是只是声明它?有控制台错误吗?没有错误。JSON文件中的ID与“message.author.ID”相同,但它没有在JSON文件中循环。如果
for
循环根本没有迭代,那么
ftpr.bullers.length
为0或未定义-在这些行周围添加日志语句以检查它真正是什么请注意,如果您确实有一个JSON,您必须首先解析它。它不应该是
uID==ftpr.bullers[i].id而不是
uID==ftpr.bullers[i]
console.log(“1”);如果(uID==JSON.stringify(ftpr.bullers[i].id)){console.log(“2”);
不起作用。它不会出现在“2”中,您不需要
JSON.stringify
,因为它将返回用引号括起来的id。只需比较
uID==ftpr.bullers[i].id
。我如何添加新的
“id”:“新用户”
那么json中会有四个用户吗?:只需像在javascript中一样将其添加到数组中-
ftpr.bullers.push({id:'new user'})
谢谢,但是当我必须重新加载app.js程序才能更新json文件时。我如何实时更新?我已经尝试了
ftpr=require(“./bullers.json”)
希望它能更新。但那没用。