Can you provide steps on loading JSON data into a JavaScript web application and then randomly selecting a word from it?

I have a text file called words.json with a long list of words, organized in alphabetical and length order.

The structure looks like this:

{"3":["ace","act","add","ado","ads"], "4":[...], ...}

(I have used ellipsis for brevity)

How do I go about loading the JSON data onto the webpage and randomly selecting a word from the list?Do I need to use jQuery for this task? What should my function look like?

Appreciate your help!

Answer №1

One way to approach this is by implementing a random word selection function like the following:

function getRandomWord(jsonStringListOfWords) {
    var words = JSON.parse(jsonListOfWords);

    var MAX_LENGTH = Object.keys(words).length;
    var wordLength = Math.floor(Math.random() * MAX_LENGTH) + 1;
    var wordIndex = Math.floor(Math.random() * words[wordLength].length) + 1;

    return words[wordLength][wordIndex];
}

This method randomly determines the length of the word first, then selects a word from the list that matches that length. However, it may not produce an even distribution among all words with various lengths.

Alternatively, here's an algorithm that ensures an equal chance for each word regardless of its length:

function getRandomWordEvenDistribution(jsonStringListOfWords) {
    var words = JSON.parse(jsonListOfWords);

    var numWords = 0;
    for (var x in words) {
        numWords += words[x].length;
    }

    var wordIndex = Math.floor(Math.random() * numWords);

    for (var x in words) {
        if (wordIndex >= words[x].length) {
            wordIndex -= words[x].length;
        } else {
            return words[x][wordIndex];
        }
    }
}

To load the JSON data, you can consider using jQuery's $.getJSON() method, which facilitates fetching JSON content from your server.

Answer №2

I successfully implemented Mash's algorithm by making two minor adjustments to it and updating the answer accordingly. You are correct in pointing out that using getJSON with jQuery makes JSON.parse unnecessary. You can see the code running on JSBin:

var words = (function() {
    var wordList, numWords;

    return  {
        load: function(data) {
            wordList = data;
            numWords = 0;
            for (var x in wordList) {
                numWords += wordList[x].length;
            }
            words.random = function() {
                var wordIndex = Math.floor(Math.random() * numWords);
                console.log(wordIndex);

                for (var x in wordList) {
                    if (wordIndex >= wordList[x].length) {
                        wordIndex -= wordList[x].length;
                    } else {
                        return wordList[x][wordIndex];
                    }
                }
            };
        },
        random: function() {
            return undefined; // or throw exception?  // not initialized yet
        }
    };
}());
var print = (function() {
    var $console = $("#console");
    return function(msg) {
        $console.text($console.text() + "\n" + msg);
    };
}());

$("#random").click(function() {
    print("Random word: " + words.random());
});

print("Random word before load: " + words.random());

$.getJSON("http://jsbin.com/ukaxec/2/js")
    .then(words.load)
    .then(function() {print("Random word after load: " + words.random());});

The $.getJSON() call fetches a small list of words, an extension of your example, also available on JSBin.

Please note, before the JSON data loads successfully, words.random functions as a placeholder, only to be replaced once the words are loaded.

However, I do question the necessity of sending the entire word list to the client if you're only utilizing it to load a single word.

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

Setting up an Express route for updating data

I am in the process of developing a MEVN stack CRUD application (Vue, Node, Express, MongoDB). I am currently working on setting up an Express route for handling updates in my app... postRoutes.post('/update/:id', async(req, res)=> { cons ...

Navigating between components using AngularJS and ExpressJS

Currently, I am embarking on a project that involves utilizing express and angularjs. To guide me through this process, I have been referring to this particular tutorial. Upon my initial attempt of running localhost:3000, I successfully loaded my index.jad ...

Creating a Dynamic Form with jQuery, AJAX, PHP, and MySQL for Multiple Input Fields

Success! The code is now functional. <form name="registration" id="registration" action="" method="post"> <div id="reg_names"> <div class="control-group"> <label>Name</label> <div class= ...

Incorporating SCSS directly in React component along with material-ui styling

I'm having trouble incorporating styles into my React component. I'd prefer to use SCSS instead of either using the withStyle function or importing a plain CSS file into a JS file. For instance, I would like to import my SCSS file into ButtonCom ...

Adjust the text size of a label in material-ui

Hey everyone, I'm struggling with something here. I need to adjust the font size of the label that goes along with my textfield. So far, I've only been able to change the font size of the input itself and not the label. Here's the code for ...

Steps to position the dropdown scrollbar to the top every time it is opened

I am working with a unique drag-and-drop multi-select dropdown that only has a unique control ID. The issue I am facing is that when the dropdown is initially opened, the scroll bar is at the top. However, after scrolling down and closing the dropdown, the ...

Transferring an array object from PHP to Python

This is the code I have developed: $dataraw = $_SESSION['image']; $datagambar = json_encode($dataraw); echo '<pre>'; print_r($dataraw); echo '</pre>'; print($escaped_json); $type1 = gettype($dataraw); print($typ ...

Error: Tried to modify a property that is read-only while using the useRef() hook in React Native with Typescript

https://i.sstatic.net/jhhAN.pngI'm facing an issue while attempting to utilize a useRef hook for a scrollview and pan gesture handler to share a common ref. Upon initializing the useRef() hook and passing it to both components, I encounter an error th ...

Retrieve information from the pouchdb database

After successfully storing data in PouchDB, I'm wondering how to retrieve this information and display it in HTML using AngularJS. var db = new PouchDB('infoDB'); function getData(){ $.getJSON('test.json', function(data) { ...

Displaying an array's values in an ng-repeat using a JSON object output

I have received JSON output from an API and I want to display it using ng-repeat within a div. [ { "companyName": "abc", "namesList": [ { "name": "Jaakr1", "email": "& ...

Repetitive invocation of functions

I am presenting a listing HTML structure as follows <li class="game-box showlist" id="papp_1249" data-tag="Junior KG,Maths"> <div class="game-box-link" data-id="1249" data-active="yes" data-orientation="landscape" data-ajax="fal ...

Using JavaScript to Retrieve URLs and Identify HTTP Status Code 403

In my JavaScript code, I am attempting to retrieve a 403 Forbidden response code using JavaScript. I have tried modifying the following code, but it does not seem to be working for me: <script type="text/javascript"> var request = new XMLHttpRequ ...

Next.js encountered an error while trying to locate the flowbite.min.js file for Tailwindcss and Flowbite, resulting in a

I'm having an issue with integrating the flowbite package with TailwindCSS in my Next.js application. Despite configuring everything correctly, I am encountering an error when adding the flowbite.min.js script: GET http://localhost:3000/node_modules/f ...

An effective method for converting a string into a two-dimensional array using JavaScript

One challenge I am facing is checking from a string if a specific fruit has the correct amount on a given date. I've managed to achieve this by converting the string into a 2D array and iterating over the columns. While this method works, I can't ...

Angular is known for sending only the fields that have changed to the update method

I need help with optimizing my save method. When a user clicks SAVE, I only want to send the fields that have been changed instead of all 50+ fields on the page. This will reduce the amount of data being sent every time. Api.Admin.update({ obsoleteDat ...

What is the best way to conceal content within a URL while still transmitting it to the server using node.js and express?

I have been trying to figure out how to hide certain content from the URL, but still need to send that information to the server in my Express app. So far, I haven't found any solutions that work. For example, if I have a URL like www.abc.com/viewblo ...

What steps do I need to take to execute a script that utilizes the mootools library within an asp.net environment

I've been working on a website that includes a mail form. I'm using the Mootools 1.4.3 library along with FormCheck 1.6.js. However, when I click the button, nothing happens except for the page refreshing. I really like this form and want to make ...

Having trouble with Simplemodal showing link content in the modal window

Having trouble getting the modal window to display content from another link? I'm pretty sure I've connected them correctly using the right classes. This is the basic JavaScript provided by . jQuery(function ($) { // Load dialog on page load //$ ...

What is the solution to the problem of "Failed to execute 'json' on 'Response': body stream already read"?

enter image description here Encountered Issue: Error in processing JSON data in the Response: body stream already read The error mentioned above is a result of issues within your application's code, not due to Cypress. It occurred due to an unhandle ...

Unable to see or play local mp4 file in Ionic iOS application

I am facing an issue with my Ionic app where I am trying to show a video playing in the background. The Jaeger25 HTMLVideo plugin works perfectly for Android, but when it comes to iOS, the video simply refuses to play. The video file is located in the www/ ...