New to JSON: Why is my variable returning as undefined?

Embarking on my first JSON project has brought some challenges that I am struggling to overcome.

Here's the task at hand. I have created a basic scraper using Apify.com to extract data from a specific website. The data is presented in JSON format, and here is a snippet of what I am receiving:

[{
  "nowPlaying": "Four Corners Music Show September 16th 2019 - hosted by Melinki",
  "#error": false,
  "#debug": {
    "requestId": "aHg5UyCT6vWQhSD",
    "url": "http://www.example.com/example/",
    "loadedUrl": "http://www.example.com/example/",
    "method": "GET",
    "retryCount": 0,
    "errorMessages": null,
    "statusCode": 200
  }
}]

Transitioning back to HTML and JavaScript, I have tried to extract the 'nowPlaying' variable using the following code. However, I encounter an issue where the console log displays the same data as before, but the 'nowPlaying' variable returns as 'undefined.'

There seems to be a glaring oversight that I am unable to pinpoint, preventing me from accessing the desired data. Any ideas on how I can retrieve the text "Four Corners Music Show September 16th 2019 - hosted by Melinki," split it, and insert it into the correct HTML elements?

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        processData(this);
    }
};
xhttp.open("GET", "https://api.apify.com/v2/actor-tasks/YSMp66SiktwNXocsf/runs/last/dataset/items?token=twn8q5PnsM5s485DNtxzabdcP&ui=1", true);
xhttp.send();

function processData(data) {
    var apiData = data.response;
    console.log(apiData);
    console.log(apiData.nowPlaying);

    var programmingInfo = apiData.nowPlaying.split('-');
    document.getElementById("showName").innerHTML = programmingInfo[0]; 
    document.getElementById("host").innerHTML = programmingInfo[1];
}

Answer №1

let request = new XMLHttpRequest();
request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        processData(this);
    }
};
request.open("GET", "https://api.apify.com/v2/actor-tasks/YSMp66SiktwNXocsf/runs/last/dataset/items?token=twn8q5PnsM5s485DNtxzabdcP&ui=1", true);
request.send();

function processData(responseData) {
    let apiData = JSON.parse(responseData.response);

    console.log('apiData', apiData);
    console.log('nowPlaying', apiData[0].nowPlaying);

    let programmingInfo = apiData[0].nowPlaying.split('-');
    console.log('programmingInfo', apiData);
    document.getElementById("showName").innerHTML = programmingInfo[0]; 
    document.getElementById("host").innerHTML = programmingInfo[1];
}

Answer №2

Utilize the JSON.parse function to transform the given string into an object resembling a dictionary, as outlined in this referenced answer on Stack Overflow:

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        processData(this);
    }
};
request.open("GET", "https://api.example.com/data", true);
request.send();

function processData(response) {
    var apiResponse = response.responseText;  
    var jsonData = JSON.parse(apiResponse)[0];
    var info = jsonData.details.split('-');
    console.log(info)
    /*document.getElementById("name").innerHTML = info[0]; 
    document.getElementById("description").innerHTML = info[1];*/ // Assuming you have the corresponding HTML structure
}

Answer №3

JSON is a JavaScript object notation, which means that the text can be converted into a valid JavaScript object. However, in order for this to be possible, the text needs to be parsed first.

The information within your data.response is stored as a string, so you cannot access its properties directly using JavaScript. The solution is to use the JSON.parse function on the string and store the resulting value in a variable.

For example, consider the following:

var apiData = data.response;

Once you have done this, you can access the properties by using a combination of array and object commands, like so:

console.log(apiData[0].nowPlaying)

Answer №4

Indicate that you are expecting a JSON response :

var request = new XMLHttpRequest();
    
    request.responseType = 'json';
    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            handleData(this);
        }
    };
    request.open("GET", "https://api.apify.com/v2/actor-tasks/YSMp66SiktwNXocsf/runs/last/dataset/items?token=twn8q5PnsM5s485DNtxzabdcP&ui=1", true);
    request.send();
    
    function handleData(data) {
        var apiData = data.response;
        console.log(apiData);
        console.log(apiData[0].nowPlaying);
    }

Answer №5

By following Oleg's example, I was able to successfully implement the solution. It simply required parsing the data into JSON format and making the request correctly.

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

How can we avoid repeated evaluations by using memoization in a function?

Currently, I am working on a jQuery function designed to switch HTML elements based on specific viewports. The concept is quite simple: <div data-swap-for="#element" data-swap-on="phone"></div> This code snippet will insert the element with t ...

Automate table column width adjustments in HTML using Selenium WebDriver

As of now, I am working on automating the process of increasing the width of an HTML table column using Selenium WebDriver. I discovered that I can retrieve the coordinates of x and y by using findElement(By.cssSelector("<Css locator>").getLocation( ...

Transform the snake code by incorporating a visual image as the face of the serpent

Can someone help me change the snake's face to an image instead of a color fill in this code? And how can I add arrows for mobile compatibility? (function() { // Insert JS code here })(); // Insert CSS code here This code snippet includes functi ...

Is there a way to insert a secured page right before accessing the dashboard?

I am trying to create a locked page that will display a message when users access the web app from a mobile device and load a mobile layout page displaying a message like mobile is not supported. I was considering using document.addEventListener('DOMC ...

Update the division by clicking the button with a randomly generated JavaScript string element

Trying to solve a unique problem here as none of the proposed solutions on similar questions have worked for me. Apologies if I'm missing something, I'm new at this. The issue is with loading an empty div on my page using javascript and strings ...

Error message: JSON.parse encountered an unexpected "<" token at the start of the JSON input

Currently, I am looping through an object and sending multiple requests to an API using the items in that object. These requests fetch data which is then stored in a database after parsing it with JSON.parse(). The parsed data is sent to a callback functio ...

Refreshing the settimeout function through a click event

I'm working on a feature where I use setTimeout to dynamically change the font size of paragraphs. My goal is to have the font size reset when the user clicks on the "reset" button or initiates the timer again. However, I've encountered an i ...

Trouble presenting specific data values from JSON

Within my PHP file, I have the following code: $data = array(); while ($row = mysql_fetch_array($result, true)) {$data[] = $row;}; echo json_encode($data); This code generates the JSON array shown below: [ { "record_id": "4", ...

Updating the index of an array in MongoDB using Node.js proves to be a challenging task

Currently, I am working on creating an API for a bus ticketing system. However, I am facing difficulties in getting it to function properly in Node.js. [ { "id":1, "hour" : "7:30am" , "seats" : [ 0 , 0, 0, 0, 0 , 0, 0, 0, 0 , 0 ...

Creating a unique JavaScript script that gradually adjusts the background color using the setTimeout() function

Is there a way to create a function that continuously changes the background color every 15 seconds by picking colors from an array that starts over once all colors have been used, without having the function run just one time? $(document).ready(() => ...

Having trouble setting up Strongloop for Loopback v.3 on macOS Catalina?

I'm currently in the process of understanding Loopback v3 (which is being utilized on a project site where I'm actively involved), and I'm attempting to follow the tutorials provided. One of the crucial steps involves installing Strongloop ...

Sharing socket data between different namespaces in Socket.ioSocket.io enables the

Is there a solution to sharing data set in a socket in one namespace and accessing it on another namespace? While I understand that data can be attached to the socket object itself, a problem arises when trying to access the data in a different namespace. ...

Creating Structure with Highcharts - Sorting Through Unprocessed Data

In reviewing various demos of highcharts, I noticed that they all tend to adhere to a fairly straightforward data structure: Categories,Apples,Pears,Oranges,Bananas John,8,4,6,5 Jane,3,4,2,3 Joe,86,76,79,77 Janet,3,16,13,15 However, the data I have doesn ...

Angular displays error ERR_UNKNOWN_URL_SCHEME when attempting to retrieve an image saved in a blob

As I transition my app from Electron to Angular, one of my main objectives is to display an image uploaded by a user. Here's how I attempted to achieve this: page.component.ts uploadImageFile(){ fileDialog({}, files =>{ //Utilizing the fileDi ...

What is the best way to ensure the network is idle after clicking on an element in puppeteer?

Is there a way to wait for network idle after clicking on an element in puppeteer? const browser = await puppeteer.launch({headless: false}); await page.goto(url, {waitUntil: 'networkidle'}); await page.click('.to_cart'); //Clicking o ...

Linking Java objects with Node.js variables

In this snippet of code, I am utilizing the 'java' module in node.js to create Java objects. Specifically, I am creating four Java objects and aiming to consolidate them as a single object by using the variable 'args' to store these Jav ...

retrieving a URL with the help of $.getJSON and effectively parsing its contents

I seem to be struggling with a coding issue and I can't quite figure out what's wrong. My code fetches a URL that returns JSON, but the function is not returning the expected string: function getit() { var ws_url = 'example.com/test.js&ap ...

Exploring various ways to implement JavaScript animations for multiple traveling effects

I have a concept for an interactive bug animation. My idea involves having five bug images fly in from the side of the screen, bounce around randomly, and bounce off the edges. Each bug should have a unique starting position and direction. To kick things ...

Move a <div> using a handle (without using JQuery)

I devised a plan to create a moveable div with a handle and came up with this code snippet: var mydragg = function() { return { move: function(divid, xpos, ypos) { divid.style.left = xpos + 'px'; divid.style.top = ypos + &apo ...

Error: The term "Worker" is undefined in a new Nextjs project

I'm currently looking into an issue where I am attempting to import a webpacked javascript file into a NextJS project that utilizes Worker, but I keep encountering the error message ReferenceError: Worker is not defined. I've simplified it down t ...