Json in js

我做了一个js程序,从1—50 Select 一个"advice number". 它需要一种连接json文件的方法.

Js file:

 Advice_number =  Math.floor(Math.random() * 50 ) + 1


console.log(Advice_number)
function Advice_picker() {


  
}


Json file:

[
    "When in the backrooms, keep your eyes low, for the walls have ears and the floors have eyes.",
    "Beware the flickering lights, for they are whispers of entities unseen.",
    "Navigate the endless halls with caution, for each turn may lead to another layer of despair.",
    "In the backrooms, silence is your ally. Speak softly, lest you awaken something that slumbers.",
    "Find solace in the quiet corners, but never linger for too long, for the stillness may consume you.",
    "Mark your path with care, for the backrooms shift and twist, leading even the most vigilant astray.",
    "Trust not the echoes, for they may lead you deeper into the labyrinth, where escape is but a fleeting dream.",
    "When all seems lost, seek the flicker of a distant light. But beware, for not all beacons lead to salvation.",
  ]
  

...

I have more in the json file

我试着寻找内置函数,但没有找到任何. 我的目标是,它 Select 的数字,它记录一个 * 随机 * advice.

如果你知道任何功能,这将有助于你,请告诉我.

推荐答案

你可以像这样在Javascript中使用JSON文件.

    // Import the file system module
    const fs = require('fs');
    
    // Read the JSON file
    fs.readFile('data.json', 'utf8', (err, data) => {
        if (err) {
            console.error('Error reading file:', err);
            return;
        }
    
        try {
            // Parse the JSON data
            const jsonData = JSON.parse(data);
    
            // Access the data from the JSON object
            const adviceArray = jsonData.advice;
    
            console.log(adviceArray);

        } catch (error) {
            console.error('Error parsing JSON:', error);
        }
    });

Javascript相关问答推荐

在JS中获取名字和姓氏的首字母

为什么JavaScript双边字符串文字插值不是二次的?

如何在NightWatch.js测试中允许浏览器权限?

如何将拖放功能添加到我已自定义为图像的文件输入HTML标签中?

JS生成具有给定数字和幻灯片计数的数组子集

如何修复内容安全策略指令脚本-SRC自身错误?

如何访问Json返回的ASP.NET Core 6中的导航图像属性

我们如何从一个行动中分派行动

使用GraphQL查询Uniswap的ETH价格

闭包是将值复制到内存的另一个位置吗?

如何使用JavaScript拆分带空格的单词

如何在HTMX提示符中设置默认值?

如果一个字符串前面有点、空格或无字符串,后面有空格、连字符或无字符串,则匹配正则表达式

删除元素属性或样式属性的首选方法

背景动画让网站摇摇欲坠

Refine.dev从不同的表取多条记录

ReactJS在类组件中更新上下文

如何使用useparams从react路由中提取id

验证Java脚本函数中的两个变量

使用JavaScript或PHP从div ID值创建锚标记和链接