首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从js文件访问json文件数据

如何从js文件访问json文件数据
EN

Stack Overflow用户
提问于 2021-07-06 14:45:00
回答 3查看 91关注 0票数 0

我正在开发一个不和谐的机器人,当用户发送特定的消息时,我想从我的dactylo.json文件中随机发送一个句子。但是,当试图从这个文件访问数据时,我会得到一个“未定义的”错误,因为它无法读取我的json文件。我看了很多以前的问题,但找不到一个帮助我的答案,尽管它帮助了其他人。我肯定我错过了什么但我似乎找不到什么..。

下面是我来自dactylo.json的代码:

代码语言:javascript
运行
复制
{
    "sentences":[
        {
            "sentence": "Un dragon gradé dégrade un gradé dragon.",
            "top":"0",
            "player":"Personne"
        },
        {
            "sentence":"Le mur murant Paris rend Paris murmurant.",
            "top":"0",
            "player":"Personne"
        },
        {
            "sentence":"Le cricri de la crique crie son cri cru et critique car il craint que l'escroc ne le croque et ne le craque.",
            "top":"0",
            "player":"Personne"
        }
    ]
}

我的代码来自dactylo.js,在这里我试图获取数据:

代码语言:javascript
运行
复制
const fs = require('fs');

module.exports = {
    name: 'dactylo',
    description: 'Démarre une partie de dactylo',
    execute(message) {
        message.reply("Recopiez la phrase suivante le plus rapidement possible :")
        const data = fs.readFileSync('C:/Users/steph/Documents/Discord Bot/commands/fun/dactylo.json');

        const sentences = data.sentences;
        var sentence = sentences[Math.floor(Math.random() * sentences.length)];
        message.channel.send(sentence);
    },
};

我所犯的错误如果有帮助的话:

代码语言:javascript
运行
复制
TypeError: Cannot read property 'length' of undefined
    at Object.execute (C:\Users\steph\Documents\Discord Bot\commands\fun\dactylo.js:11:71)
    at Client.<anonymous> (C:\Users\steph\Documents\Discord Bot\main.js:42:11)
    at Client.emit (events.js:375:28)
    at MessageCreateAction.handle (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (C:\Users\steph\Documents\Discord Bot\node_modules\ws\lib\event-target.js:132:16)
    at WebSocket.emit (events.js:375:28)
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-07-06 14:47:36

您可以简单地在开头导入json文件:

代码语言:javascript
运行
复制
const dactylo = require('<path_to_json>.json');
票数 1
EN

Stack Overflow用户

发布于 2021-07-06 14:50:24

您可以使用require为您自动解析JSON

代码语言:javascript
运行
复制
const data = require('path/to/file.json');

另外,最好使用文件的相对路径,而不是绝对路径。

票数 0
EN

Stack Overflow用户

发布于 2021-07-06 14:59:56

在您的示例中,fs.readFileSync函数返回一个缓冲区,而不是像您预期的那样返回解析的json内容。

为了获得解析的JSON内容,您需要执行两个步骤:

  1. 将.json文件内容作为文本读取
  2. 用JSON.parse解析文本

下面的代码说明了它的工作原理:

代码语言:javascript
运行
复制
const jsonPath = 'C:/Users/steph/Documents/Discord Bot/commands/fun/dactylo.json';
const jsonText = fs.readFileSync(jsonPath, "utf8"); 
const jsonObject = JSON.parse(jsonText);
console.log(jsonObject.sentences.length);   // 3

注意,传递给fs.readFileSync函数的第二个参数告诉函数将文件内容作为字符串而不是缓冲区返回。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68272681

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档