【问题标题】:How to append to JSON without an array?如何在没有数组的情况下附加到 JSON?
【发布时间】:2021-02-22 13:31:55
【问题描述】:

我正在使用 Discord.JS 编写一个 Discord 机器人,并且对它相当陌生。 (从今年夏天开始)

我有一个无线电机器人供我和我的朋友使用,我让它加入频道并从 JSON 读取并正常播放音乐。

我想要它做的是,我可以通过命令添加到stations.json 文件,然后一切都会从那里更新。

这是stations.json

{
    "b101":
        {
            "command":"b101",
            "link":"https://playerservices.streamtheworld.com/api/livestream-redirect/WBEBFMAAC.aac",
            "name":"Philly's B101"
        },
}

这是每个站的格式 这里是play.js

module.exports = {
    name: "music!play",
    description: "Find a music stream and play it",
    execute(msg, args, client) {
        function validURL(str) {
        var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
            '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
            '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
            '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
            '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
            '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
        return !!pattern.test(str);
        }
        
        if (args.length === 0)
        return msg.reply('supply a station please');

        if (msg.member.voice.channel) {
            let stationsJson = require('./stations.json');
            const isStation = stationsJson.hasOwnProperty(args[0])
            if (isStation) {
                const station = args[0]
                msg.member.voice.channel.join()
                .then(connection => {
                    const link = stationsJson[station].link
                    const title = stationsJson[station].name
                    msg.reply(`Connected! Playing ${title}`)
                    connection.play(link);
                });
            } else {
              // this is just manual link input here
            }
        } else {
        msg.reply('You are not in a voice channel!');
      }
    }
}

最后,这里是add.js。添加电台的命令。

const fs = require('fs')
var command = args[0]
var link = args[1]
var name = args.slice(2,20).join(" ")

fs.readFile('./commands/stations.json', function (err, data) {
  if (err) throw err

  var json = JSON.parse(data)
  json.stations.push(
    {
      "${command}": {
        "command": command,
        "link": link,
        "name": name
      }
   });

json = JSON.stringify(json);
fs.writeFile('./commands/stations.json', json, 'utf8', function (err) {
  if (err) throw err
});

这是我迄今为止尝试过的,但我必须将它放在一个数组中,当我尝试从 play.js 播放时这不起作用。

感谢您的帮助!

【问题讨论】:

  • 在你的 add 函数中,当你推送到数组时,你用引号写了这个 "${command}",如果你希望你的变量被附加到你应该替换的字符串中,这将不起作用${command}" by `${command}` 无论如何这在您的情况下不是必需的,因为您的字符串仅包含命令名称,因此您可以只写变量的名称
  • 当您发布问题时,请尝试添加更简洁的代码。删除代码中所有不必要的部分,以便每个想要提供帮助的人都可以专注于重要部分。例如,您不需要在 .json 文件中添加所有内容。您可以删除所有验证码等,因为它们与您的问题无关。
  • 好的,谢谢!问这些问题我有点陌生。我现在就修复它

标签: javascript node.js json discord discord.js


【解决方案1】:

我发现你有一个错误add.js 文件。

您的 json 文件中没有 json.stations。如果您有类似的东西,它将可用:

// stations.json
{
  stations: [{
    "b101": {
      "command":"b101",
      "link":"https://playerservices.streamtheworld.com/api/livestreamredirect/WBEBFMAAC.aac",
      "name":"Philly's B101"
    }
  }]
}

现在json.stations 是可能的,它是数组。

如果你想给一个对象添加一些东西,你应该使用

json[command] = {
  `${command}`: {
    "command": command,
    "link": link,
    "name": name
  }
}

【讨论】:

  • 如何更新我的play.js 文件以从 JSON 文件播放?
  • @zangw 在问题 35389060 中说:“require 是同步的,并且只读取一次文件,随后的调用会从缓存中返回结果。”也许您可以尝试用文件系统调用替换您的需求。
  • 好的,现在是我的午餐时间,我会尝试所有这些修复。谢谢!
猜你喜欢
  • 2022-11-14
  • 2018-08-27
  • 2022-10-07
  • 2017-09-01
  • 2018-06-02
  • 2020-03-11
  • 2015-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多