Choose a word at random from a JSON string

Utilizing JSONP, I have successfully retrieved a list of words from an external source to randomly select one for use in a game. The current source being used is as follows:

function processResult(obj) {               
    console.log(obj);
    var data = JSON.stringify(obj);
    console.log(data);
}

var script = document.createElement('script');
script.src = 'http://testhangmangame.net76.net?jsonp=processResult';
document.body.appendChild(script);

I am curious about the feasibility and method for extracting a single word from that string. Thank you in advance!


Sample JSON response:

{
    "words": [
        "Finitely",
        "Misleading",
        "Dinning",
        "Energizing",
        "Untruest",
        "Menorah",
        "Ghoulish",
        "Realism",
        "Caliphate",
        "Buttercup",
        "Oratorio",
        "Prefix",
        "Gaming",
        "Preshrunk",
        "Harmed",
        "Loop",
        "Banknote",
        "Doily",
        "Rest of words removed"
    ]
}

This JSON is enclosed within processResult( ... );.

Answer №1

When working with JSONP, the result is automatically converted into a regular JavaScript object, making JSON unnecessary. All you have to do is extract the array from the object and use the common method for selecting a random element.

function handleResult(data) {               
    var items = data.items;
    var random_item =  items[Math.floor(Math.random() * items.length)];
    console.log("Random item selected: "+random_item);
}

Answer №2

In the event that the API is properly constructed and the Json response field contains an array:

let array = json['array_field'];
let randomElement = array[Math.floor(Math.random() * array.length)];

If the Json response returns a string, you will need to convert it into an array first:

let stringArray = json['string_field'].split(/\W{1,}/); // Splitting by whitespace
let randomString = stringArray[Math.floor(Math.random() * stringArray.length)];

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

Obtaining the latest state within the existing handler

In my React application, I have a handler that shuffles the state entry data: state = { data:[1,2,3,4,5] }; public handleShuffle = () => { const current = this.state.data; const shuffled = current .map((a: any) => [Math.random() ...

What is the best way to customize multiple checkboxes in React Native?

I need help with implementing checkboxes in my app using react-native-check-box. I have tried creating 4 checkboxes, but the text inside them is not aligning properly. The boxes are rendering one above the other instead of staying on the same line. I want ...

Adjust the size of the event bar on the FullCalendar resourceTimeline view

In my implementation of FullCalendar v6, I am displaying 6 months worth of data in the calendar, with each slot representing a one-month period. The issue I am facing is that when creating an event spanning 10 days, it currently takes up the entire width o ...

How do I assign a variable to a session in Express.js?

I am currently working on a login form that prompts users to enter their username, password, and company name. The company name corresponds to the database name, so I need to store this information in the session during the login post request. In my opini ...

Having trouble extracting parameters from the router listen event in react-router?

Having trouble accessing the route parameter with react-router router.listen() method. It seems to fail, but I found a workaround using window.location.pathname.split('route/')[1]. Any suggestions? I've been investigating why this issue occ ...

Unveiling the Magic Bytes: Extracting the Image File in Multer for Magic Byte Verification in Express.js

Utilizing the fileFilter option within the multer plugin to determine whether an image should be saved on the server or not. Within the fileFilter function, there is a need to verify the magic bytes of these images in order to ensure they are legitimate a ...

Retrieving string-based JSON information

Within my text box, the user inputs strings separated by commas. These strings are split on the front end, then sent to the backend to retrieve data in JSON format. The interesting part is that when I directly entered the key of the JSON, like this, it wo ...

Using Swagger with Next.js

Is it possible to generate Swagger documentation for API routes in NEXT.js? I am working with Next.js for both front-end and back-end tasks, and I am interested in creating a Swagger documentation for the APIs implemented in Next.js. ...

Changing the value of a variable after iterating through an array in JavaScript

I'm just getting started with programming and teaching myself. I'm struggling to grasp how to update a variable by iterating through an array. Here's an array containing the best pies, each with its own price: [blueberry, strawberry, pumpk ...

On mobile devices, the alignment of text in Bootstrap doesn't appear as intended

I'm creating a portfolio website for showcasing my design projects from university. The text in the "my work" section is centered, but it seems misaligned with other elements like buttons when the window width is reduced. What could be the issue? Cod ...

Refreshing a Next.js website on-demand using the Django model's save function

My current setup involves a next.js website deployed on Vercel, which retrieves data from an API provided by Django. Utilizing a new feature in Next.js known as Incremental Static Regeneration On-Demand, I am able to rebuild specific pages without having t ...

Storing information in an array and converting it to JSON using dual nested foreach loops in PHP

I need to retrieve data from two tables that have no relation. I am using a foreach loop to fetch all the data by a selected key and combine the data from both tables into an array. How can I store the data in an array while fetching data from two tables u ...

Verify the text file for any data, and if it contains any, display it on the web browser using JavaScript

I have a program in C that works with a temperature sensor. It creates a file to store the temperature and indicates whether it falls within specific values. I want to display this data on a web browser and update it every 5 minutes. I'm looking for ...

Seeking assistance with producing results

Is there someone who can provide an answer? What will be the output of the code snippet below when logged to the console and why? (function(){ var a = b = 3; })(); console.log("Is 'a' defined? " + (typeof a !== 'u ...

Using jQuery to load data into a combo box from a JSON file

Ensure that the list of countries is stored in the countries.json file. When attempting to load the countries into the combo box from the json file, no results are being displayed. Here are the details of the code. The countries should be visible in the co ...

Formik causing malfunction in MUI DatePicker functionality

In my React project, I am using Formik to manage form processing and MUI UI components for the user interface. While I can select the day and month, I'm experiencing an issue with the year part not updating. Even when I manually type in a year in the ...

Although hiding and showing elements in jQuery is quick, the rendering engine is too sluggish

Experiencing a performance problem when toggling the visibility of all "tr.content" elements within a complex dom structure like this:    <tbody class="collapsible">        <tr class="handler">            <td>Collaps ...

Avoiding mocking a specific module with jest forever

Our codebase heavily relies on underscore in various parts, and I prefer to avoid mocking it. I'm aware that I can use jest.unmock('underscore'); in each test that utilizes underscore. Is there a method to unmock underscore across all tests ...

Tips on how to transform an <input type="text"> element into a <tr> element using jquery

I am currently working on updating a row using jQuery Ajax. Whenever the Edit button is clicked, it switches the <tr> element to <input type='text'>. I have utilized the .Change method which triggers successfully, but my goal is to r ...

Working with Multi-dimensional Arrays in JSON Using Mysql

What is the best way to store JSON code in a MySQL field? I am looking to store user data (with user_id as the key) including three values: name, age, and sex. 145:"name,age,sex", 148:"name,age,sex", 200:"name,age,sex" I am currently using MySQL version ...