Iterating through a JSON object using an API loop

Just starting out in JS and I am attempting to use a for loop to combine all the 'text' from various JSON objects into one cohesive paragraph. For example, it should read like this: "Hello, and welcome to the Minute Physics tutorial on basic Rocket Science. Before we get started, I'd like to quickly announce that I'm now making these videos at the perimeter institute for theoretical physics"

function loadRequest() {
    var data = null;

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var obj = JSON.parse(this.responseText);
        for(var i = 0; i < json.length; i++) {
            var obj = json[i];
        document.getElementById("text").innerHTML = obj.text;
    }
}
}

xhttp.open("GET", "https://fakeapi.p.rapidapi.com/sample", true);
xhttp.setRequestHeader("x-rapidapi-host", "fakeapi.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "APIKey");

xhttp.send();
  
  
}

JSON:

"[ { 'index': 0, 'start': 0.03, 'dur': 4.499, 'end': 4.529, 'text': 'Hello, and welcome to the Minute Physics tutorial on basic Rocket Science. Before we get started,' }, { 'index': 1, 'start': 4.529, 'dur': 4.17, 'end': 8.699, 'text': 'I'd like to quickly announce that I'm now making these videos at the perimeter institute for theoretical physics' },

Answer №1

The issues within the code are all concentrated in the for loop section.

let data = JSON.parse(this.responseText);
for(let j = 0; j < data.length; j++) {
    const content = data[j].content;
    document.getElementById("text").innerHTML += content;
}

It seems like the initial

var obj = JSON.parse(this.responseText)
statement should have been updated to use json instead of obj.

Another problem was that you were overwriting the html element with the new text each time, when you should have been using += to append to the existing text instead.

Answer №2

It seems that there is an issue with the JSON structure you have provided. I have made the necessary corrections to ensure that the response array functions correctly. Additionally, there are some coding issues that needed to be addressed as well.

Below is the updated version of the code. I hope this solution will prove to be useful for you.

const responseText = '[ { "index": 0, "start": 0.03, "dur": 4.499, "end": 4.529, "text": "Hello, and welcome to the Minute Physics tutorial on basic Rocket Science. Before we get started," }, { "index": 1, "start": 4.529, "dur": 4.17, "end": 8.699, "text": "I\'d like to quickly announce that I\'m now making these videos at the perimeter institute for theoretical physics" }]';
const json = JSON.parse(responseText);
let str = '';
for(var i = 0; i < json.length; i++) {
    str += json[i].text;
}
document.getElementById("text").innerHTML = str;
<p id="text"></p>

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

The current error message states that the function is undefined, indicating that the Bookshelf.js model function is not being acknowledged

I have implemented a user registration API endpoint using NodeJS, ExpressJS, and Bookshelf.js. However, I encountered an error while POSTing to the register URL related to one of the functions in the User model. Here is the code snippet from routes/index. ...

Getting started with TinyMCE in Nuxt: A step-by-step guide

I need to incorporate this script into my Nuxt code: <script> tinymce.init({ selector: "#mytextarea", plugins: "emoticons", toolbar: "emoticons", toolbar_location: "bottom", menubar: false ...

Having trouble posting data in node.js using MongoDB and EJS

Hey everyone, I'm currently working on creating a page with a form and text input fields. However, I'm encountering an error that says "Cannot Post". Here is my code, any help would be greatly appreciated. Why isn't it working? This is app. ...

The plugin needed for the 'autoprefixer' task could not be located

Starting out in the world of Angular 2 development can be overwhelming, especially when trying to integrate with the Play framework on the back-end side. I recently came across a helpful post by Denis Sinyakov that walks through setting up this integratio ...

Scrolling with jQuery to create a fixed navigation bar

I'm having an issue with my navbar on my website. I used CSS and jQuery to keep it fixed at the top, but now when I click on a menu item, it doesn't scroll to that section of the page. Can anyone help me troubleshoot this problem? ...

Creating a JSON Array in Java with CDL.toJSONArray is not possible

My CSV data has the following structure: Name,Title,Class,Users Global D&A,W,clLevel,"ADMIN" Template Manager,X,clLevel,"G,ADMIN" Test Manager,W,clLevel,"G,ADMIN" I am attempting to convert this data to JSON using Java, but I have not been successful ...

Arrangement of jQuery On Events and Triggers

Consider the code snippet below: $('body').on('hellothere', function(){ console.log('execution complete.'); }); $('body').triggerHandler('hellothere'); The abov ...

Navigating through the year selection with your keyboard

By default, a dropdown menu containing years allows for keyboard navigation. For example, if you type in 1992 while the dropdown is selected, it will automatically move to that specific year option. I am curious to know if there is a way to activate a two ...

Retrieve the quantity of files in a specific directory by implementing AJAX within a chrome extension

I need assistance with obtaining the count of images in a specific directory using JS and AJAX within my chrome extension. My current code is included below, but it does not seem to be functioning as expected since the alert is not displaying. main.js .. ...

The issue of excessive new lines appearing during JSON encoding is encountered when responding

When using the print_r method to display an array: Array ( [0] => Array ( [id] => 44 [item_level] => 0 [position] => 10 [parent_position] => [title] => PHP Tutorial ...

Issue with Many to Many Relation Query in Objection JS, Postgres, and Express Resulting in 'TypeError: Cannot Read Property 'isPartial' of Null' Error

I have a challenge connecting the 'products' table to the 'tags' table using a many-to-many relationship structure with the 'products_tags' table. Upon executing const product = await Product.relatedQuery('tags').fi ...

What is the significance of using parentheses around a function in JavaScript?

Currently, I am developing an application using Java and JavaScript, and while reviewing some code today, I came across a segment that seemed confusing to me. var myVariable = (function(configObj){ var width = configObj.width; var height = config ...

Unable to locate the required conditional template for the 'mdRadioButton' directive due to the absence of the 'mdRadioGroup' controller

I am currently working on developing a custom directive that will help me display questions within a survey. Given the multiple types of questions I have, I decided to create a single directive and dynamically change its template based on the type of quest ...

Using Android to extract information from JSONObject

I'm currently working on retrieving data from a database in Android. My setup involves using PHP files to process the database information and return it as a JSON object, which I then access in my Android code. One part of my code looks like this: J ...

The functionality of Node.js middleware is not functioning correctly

My module contains Routes, and I want to verify access before allowing users to proceed. Within the Routes module, there are two routes and two access-check functions that I want to use as middlewares: const checkUser = (req, res, next) => { if (!us ...

Individual Ajax data

Starting out with javascript, I'm a bit unsure of how to tackle this task. Essentially, I am looking to implement a for loop within the ajax data call, rather than listing each item manually. jQuery(document).ready(function() { ...

Error -1 with JSON key

I've been tirelessly seeking the solution to this issue, but it eludes me. My goal is to retrieve the value by index of a JSON string. Despite the matching key, I'm getting -1 for the index. All I want is the value "Ethan" for the key username. ...

The distinction between a keypress event and a click event

Due to my eyesight challenges, I am focusing on keyboard events for this question. When I set up a click event handler for a button like this: $("#button").on("click", function() { alert("clicked"); }); Since using the mouse is not an option for me, ...

I seem to be having trouble with my JavaScript code when attempting to search for items within

I want to implement an onkeyup function for a text input that searches for patient names from column 2 in my table. However, it seems to be not working properly as I don't get any results in return. Below are the snippets of what I have done so far. ...

Attaching a click event to an input field

Seeking to serve html files from the server without relying on template engines. Below is the script used to start the server. // script.js const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(expr ...