skip to Main Content

Json in js

I made a js program that picks a "advice number" From 1-50.
It needs a way to connect with a json file.

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

I tried looking for built-in functions but i couldn’t find any.
my goal is that for the number it picks it logs a *random *advice.

If you know any functions that will help please tell me.

3

Answers


  1. You can use JSON files in Javascript like this.

        // 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);
            }
        });
    
    Login or Signup to reply.
  2. On client side you have to use assert as it is shown in this article.
    Also you have to use type="module" in the script tag in HTML document.

    import advices from "./path/to/data.json" assert { type: "json" };
    const adviceNumber =  Math.floor(Math.random() * 50 ) + 1;
    
    console.log(adviceNumber);
    
    function advicePicker() {
      return advices[adviceNumber];
    }
    

    Or you can use fetch() function, as it is also described in above mentioned article:

    const adviceNumber =  Math.floor(Math.random() * 50 ) + 1;
    
    fetch("./path/to/data.json")
      .then((response) => response.json())
      .then((data) => {
        console.log(data[adviceNumber]);
      })
      .catch((error) => console.error("Error loading JSON file", error));
    
    Login or Signup to reply.
  3. If you are using javascript on client side, you can try with fetch.

    fetch('data/data.json') // Adjust the path to match the location of your JSON file
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json(); // Parse JSON data from the response
        })
        .then(data => {
            // Access the data from the JSON object
            const adviceArray = data.advice;
            console.log(adviceArray);
        })
        .catch(error => {
            console.error('Error fetching JSON:', error);
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search