How can I extract the return value of a JSON object and store it in a variable?

I am attempting to develop a dynamic chart by utilizing data retrieved from a function housed inside a JSON object.

The JSON object is fetched through the Relayr Javascript API, and looks like this:

relayr.devices().getDeviceData({
            token: toke,
            deviceId: Candle1_deviceId,
            incomingData: function (data) {
                console.log(data.readings[0].meaning);
                console.log(data.readings[0].value);
                return data.readings[0].value;
            }
        });

My objective is to incorporate data.readings[0].value into the chart as shown below:

window.onload = function () {

        var dps = []; // dataPoints

        var chart = new CanvasJS.Chart("chartContainer", {
            title: {
                text: "Westminster Cathedral Building Movement Data"
            },
            data: [{
                type: "line",
                dataPoints: dps
        }]
        });

        var xVal = 0;
         var yVal;
        var updateInterval = 100;
        var dataLength = 500; // number of dataPoints visible at any point

        var updateChart = function (count) {
            count = count || 1;

            for (var j = 0; j < count; j++) {
                yVal = yVal + relayr.devices().getDeviceData.incomingData;
                dps.push({
                    x: xVal,
                    y: yVal
                });
                xVal++;
            };
            if (dps.length > dataLength) {
                dps.shift();
            }

            chart.render();

        };

        updateChart(dataLength);

        
        setInterval(function () {
            updateChart()
        }, updateInterval);

    }

The code above is adapted from an example on CanvasJS.

Answer №1

There's no need to constantly regenerate the chart or set up a separate timer for updating it. Simply update the chart whenever new data is received from relayr by following these steps:

var yVal = 0, xVal = 0, dataLength = 500;
var dps = []; // collection of dataPoints

var chart = new CanvasJS.Chart("chartContainer", {
    title: {
        text: "Westminster Cathedral Building Movement Data"
    },
    data: [{
        type: "line",
        dataPoints: dps
    }]
});
relayr.devices().getDeviceData({
    token: toke,
    deviceId: Candle1_deviceId,
    incomingData: function (data) {
        console.log(data.readings[0].meaning);
        console.log(data.readings[0].value);
        yVal = data.readings[0].value;
        dps.push({
            x: xVal,
            y: yVal
        });
        xVal++;

        if (dps.length > dataLength) {
            dps.shift();
        }
        chart.render()
        return data.readings[0].value;
    }
});

Answer №2

Implement an additional function that takes a value parameter to create your chart:

function generateChart(value) {
    // Handle the provided value

    var dataPoints = [];

    var chart = new CanvasJS.Chart("chartContainer", {
        title: {
            text: "Westminster Cathedral Building Movement Data"
        },
        data: [{
            type: "line",
            dataPoints: dataPoints
    }]
    });

    var xValue = 0;
     var yValue;
    var updateInterval = 100;
    var dataLength = 500; // Number of visible dataPoints at any given time

    var updateGraph = function (counter) {
        counter = counter || 1;

        for (var k = 0; k < counter; k++) {
            yValue = yValue + relayr.devices().getDeviceData.incomingData;
            dataPoints.push({
                x: xValue,
                y: yValue
            });
            xValue++;
        };
        if (dataPoints.length > dataLength) {
            dataPoints.shift();
        }

        chart.render();

    };

    // Generate initial set of dataPoints
    updateGraph(dataLength);

    // Update chart periodically 
    setInterval(function () {
        updateGraph()
    }, updateInterval);

}

Invoke the function outside the callback:

window.onload = function () {
    relayr.devices().getDeviceData({
        token: token,
        deviceId: Candle1_deviceId,
        incomingData: function (info) {
            console.log(info.readings[0].meaning);
            console.log(info.readings[0].value);
            generateChart(info.readings[0].value);
            return info.readings[0].value;
        }
    });
}

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

Issues with AJAX requests failing to fire with the latest version of jQuery

A small script I have checks the availability of a username in the database, displaying "taken" if it's already taken and "available" if it's not. The code below works perfectly with jQuery v1.7.2. However, I need to update it for jQuery v3.2.1. ...

Analyzing DynamoDB Query

I am on a mission to recursively analyze a DynamoDB request made using the dynamo.getItem method. However, it seems that I am unable to locate a similar method in the DynamoDB SDK for Node.js. You can find more information about DynamoDB SDK at http://do ...

Unexpected Error with Background Position Variable

Hello, I am attempting to create an animated background effect that moves up and down using the .animate() and .hover() methods in jQuery. Within my DOM, there is a div with id="#menu" containing a UL list where each item has a background positioned at dif ...

Is it possible to utilize a JSONPath expression to retrieve an altered value from a selected element?

I have a JSON containing key-value pairs separated by pipes, and I need to extract a specific value using a JSONPath expression in my script. My goal is to retrieve the "Job Titles" located in the third position of the "Rows" object by utilizing JSONPath. ...

A Beginner's Guide to Understanding Elasticsearch, Logstash, and Kibana without Technical Jargon

I am confused. I understand that Logstash allows us to input csv/log files and apply filters using separators and columns. The output is then sent to elasticsearch for use with Kibana. However, I'm unsure about whether or not we need to specify an ind ...

Issue encountered when attempting to insert data via node into MySQL database

As a new Node developer, I am in the process of building some initial applications. Currently, I am working on inserting records into a MySQL database using Node. Below is an example of my post method: router.post('/add',function(req,res){ c ...

Troubleshooting: Datepicker not appearing in Bootstrap

Here is the detailed markup for the datepicker component: <div class="form-group row"> <div class="col-xs-3 col-md-offset-9"> <label class="control-label">Pick Date</label> <div class="input-group date" id="dp3" data-d ...

Challenges associated with parsing JSON structures that have nested lists and dictionaries

I'm currently in the process of writing a script that will generate a CSV file based on parsed JSON data. While I have successfully managed to read the JSON, I've hit a roadblock with a TypeError: list indices must be integers, not dict. Previou ...

Having trouble with loading JavaScript during ng build --prod process

The JavaScript file I'm using for multiple emails (multiple_emails.js plugin) works well with ng serve. Here is my code: (function( $ ){ $.fn.multiple_emails = function(options) { // Default options var defaults = { ...

Steps for generating a fresh JSON object during each loop iteration

Currently, I'm developing a feature that will utilize my daily work hours and contract start/end dates to populate a calendar with my work schedule. However, I've encountered an issue when dealing with multiple shifts on the same day. For example ...

Tips for managing Express.js callbacks and modifying an object's property from within a function

I am currently working with two JavaScript files. I have successfully retrieved data from MongoDB using the method bookDao.getActiveBookByCategoryId(). The Issue I Am Facing: Within the categoryDao.js file, I am attempting to update the resultJson.book_c ...

I am looking for information on how to properly handle HTTP errors in Axios when utilizing a blob responseType in VueJs

Using the blob responseType with Axios in my VueJS app allows me to download a document from the server. Everything works fine when the response code is 200, but problems arise when there's an HTTP error. I find it challenging to read the status code ...

Can you explain the meaning of arguments[0] and arguments[1] in relation to the executeScript method within the JavascriptExecutor interface in Selenium WebDriver?

When utilizing the executeScript() method from the JavascriptExecutor interface in Selenium WebDriver, what do arguments[0] and arguments[1] signify? Additionally, what is the function of arguments[0] in the following code snippet. javaScriptExecutor.ex ...

Reversing the order of input-group-addon and input in bootstrap on mobile devices

I attempted to adjust the layout of a bootstrap input-group-addon on mobile devices by using two input elements and manipulating their display and visibility properties. From a design standpoint, I achieved the desired result as the input is now positione ...

Is there a way to retrieve the current route on a custom 404 page in Next.JS?

I have set up a custom 404 page for my Next.JS application (404.js). I want to display a message stating The route <strong>/not-a-route</strong> does not exist, but when I use Next.js's useRouter() and router.pathname, it incorrectly ident ...

Unexpected color changes when hovering over sparkline graphs

One of the jquery plugins I'm using is called sparkline Here's an example of how I am using it: $(function(){ $("#sparkline5").sparkline([2, 8, 10, 22], { type: 'pie', height: '140', sliceColors: [ ...

"Converting PostgreSQL data into a PHP array with the column serving as the index

Is it possible to return a JSON object directly from a PostgreSQL query? Let's say the query produces results like this: who count ================= mary 2 had 9 a 12 lamb 9 The database has columns "who" and "count." I ...

Place a div element directly into a specific cell within the table

How can I place the following div <div class="inner"> <p>The first paragraph</p> <p>The second paragraph</p> </div> into a specific cell within a table? I am open to using either plain JavaScript or jQuery, althou ...

Transforming a React, Redux, and MUI Menu into an Electron Application

I'm in the process of transforming a web-based React + Redux + MUI application into an Electron app. The original app features a main AppBar with multiple dropdown menus, each containing menu items that interact with the app's Redux store. While ...

Implementing a soft transition to intl-tel-input plugin

This tel-input plugin was developed by Jack O'Connor. You can find the plugin here: https://github.com/Bluefieldscom/intl-tel-input I have observed that the flags take approximately one second to download, and I would like to enhance this process wi ...