Generating Random Values from a JSON Data in nodejs

My dilemma involves a massive JSON file full of 75,000 quotes. The file can be accessed here: . I am looking for a way to randomly select a quote from this file and display it in an HTML document. I am currently working with Node.js. Could someone provide guidance on how to accomplish this task?

Answer №1

To access the content, you must save the file onto your device as the website does not allow external requests.

const fs = require("fs");

function generateRandomIndex(size) {
    return Math.floor(Math.random() * size);
}

const quotesCollection = JSON.parse(fs.readFileSync("quotes.json", { encoding: "utf-8", flag: "r" }));

const selectedQuote = quotesCollection[generateRandomIndex(quotesCollection.length)];

document.getElementById("quote").innerHTML = `"${selectedQuote.QUOTE}" - ${selectedQuote.AUTHOR} (genre: ${selectedQuote.GENRE})`;

<span id="quote">Your chosen quote will appear here</span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to configure raycaster layers within Three.js framework

While attempting to configure the raycaster layer to only cast on a single layer, as outlined in the threejs documentation: - I encountered the following error Uncaught TypeError: Cannot read properties of undefined (reading 'set') What could b ...

Attempting to scale the div element to a portion of the total page's width and height

Is there a way to make the height of div elements a percentage of the body height? I am currently using Bootstrap version 5.3 and have managed to set the body element to be 100% of the viewport. However, all other div elements are staying at a fixed size o ...

What is the best way to extract a value from a string containing a list of maps?

I am currently facing a requirement where I need to extract values from a map in the following format: "{xyz=True, abc=asd-1123, uvw=null}" The challenge is to retrieve these values from a string representation of the map. I have attempted usi ...

What is the process for obtaining a pristine window object?

My bookmarklet utilizes the window.open method, but sometimes websites modify this method which causes unpredictable behavior when running the bookmarklet. I'm looking for a way to obtain an "untouched" window object. I attempted to inject a new ifra ...

Exploring Mongoose queries for nested model objects

I am currently working on a product filtering logic for my project. Within the Products model, I have implemented a search functionality to filter products based on query parameters. These parameters are stored in an array of settings (queryConditions) if ...

symfony submit form without sending request

I'm trying to make a request without using a submit button, only by selecting an option. So far, I've attempted to achieve this using JavaScript but haven't had any success. Here's my form code: $form = $this->createFormBuilder() ...

Tool to stop automatic logouts on websites

In the web application where I work, users are automatically logged out after a period of inactivity. Unfortunately, I am unable to control this feature. The code responsible for logging the user out is as follows: var windoc = window.document; var timeou ...

Different approach instead of using margins for HTML email design

Is there a way to replace the following in an HTML email: margin-top: -40px; This code works well in Webmails but not in Outlook! I have tested it on different versions of Outlook and always get the same results. *I need this to position a second tab ...

Experiencing difficulties when trying to upload images onto the inner surface of a spherical object using Three.js

I am new to working with Three.js and this is my first major project. Despite its simplicity, I have been struggling for the past two weeks trying to resolve an issue. My goal is to create a model of the Earth in Three.js along with a star field, but I can ...

Highlight and trim lengthy text using React

Imagine I have a lengthy text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo con ...

Bovine without Redis to oversee queue operations

Can Bull (used for job management) be implemented without utilizing Redis? Here is a segment of my code: @Injectable() export class MailService { private queue: Bull.Queue; private readonly queueName = 'mail'; constructor() { ...

What is the best way to extract the content located between two specific HTML elements?

<div class="container"> <a href="#" class="link">asd</a> [Please extract this specific text] <a href="#" class="link">asd</a> Other unrelated content. </div> Is there a way to access the text inside certain elem ...

Ways to transmit the appropriate model

Using AJAX, I am sending a model to the server via a POST request. I have defined a model and a controller method for processing it. public class TestDto: BaseDto { [Required] public ProductGalleryDto GalleryProduct { get; set; } public int ...

I'm overwhelmed by the concept of linear gradients

I've been struggling to recreate the CSS gradient, so here's what I'm aiming for: https://i.sstatic.net/4gIHV.png Here are the details: Gradient colors: Start color: #1696B6 with 50% opacity End color: Black with 100% transparency https:// ...

Exploring the World with JQuery AJax on Google Maps

I am encountering an issue with a basic web page where it performs two AJAX requests using JQuery to retrieve parameters and then updates the Latitude and Longitude for a Google Maps element. However, I am noticing that after the AJAX calls are completed, ...

JavaScript - Accessing a static property through an object instance

UPDATE - The question title has been updated to accurately describe the issue I've decided to optimize my node.js application by implementing more OOP principles in my code. Previously, the mysql driver and connection (pool) were situated at the top ...

For each array element that is pushed, create and return an empty object

I am encountering an issue with an array where the objects are being generated by a push operation within a function. Despite successfully viewing the objects directly in the array, when I attempt to use forEach to count how many times each id uses the ser ...

What could be causing my form to malfunction when sending? Comparing [(ngModel)] to form submission in Angular 2+

I recently made changes to the form implementation on my login screen. Instead of binding to the inputs [(ngModel)] in the backend, I now pass the form itself. Although this change allowed the original tests to pass, it caused issues with the actual app f ...

Exploring the code within the $(function () { ... }) block

I am working with a .NET web control that contains some JavaScript code structured as follows: <script type="text/javascript"> function doSomethingImportant() { // Code for an important task... } $(function () { // Som ...

Is there a way to calculate the upload ratio for a file upload progress bar without using a plugin or pre-made solution

Can someone provide guidance on how to create a file upload using iframe with an ajax effect? I am specifically looking for a way to track the uploading progress. While there are many plugins available, I would appreciate some ideas or examples to achiev ...