Create an Interactive Data Visualization with JSON using CanvasJS Charts

Having some trouble creating a chart using CanvasJS.

After fetching data from the API and checking the JSON array, I encounter two errors when attempting to generate dataPoints for the graph: "data invalid" on the data field and "NaN" on the value field.

Any suggestions or hints would be greatly appreciated!

// Retrieving data
fetch('https://example.com/my/endpoint').then(response => {
  return response.json();
}).then(data => {
  // Process JSON data here
 var jsonData = data;
 // Creating Data Points
 var dataPoints = [];
 
for (var i = 0; i <= jsonData.length - 1; i++) {
    dataPoints.push({ y: new Date(jsonData[i].source_ts), x: Number(jsonData[i].xyzw) });
    console.log(dataPoints);
}

var chart = new CanvasJS.Chart("chartContainer", {
    data: [
        {
            dataPoints: dataPoints,
            type: "line",
        }
    ]
});

chart.render();
}).catch(err => {
 throw new Error( 'Failed to retrieve data' );
});

Cheers

Answer №1

Your handling of data was incorrect, resulting in the error message y:null and x:NaN.

The data contains an array of objects within an array like this: [[{}, {}, {}...]], so you must iterate through it accordingly.

Here is a sample code snippet for proper iteration:

  data.forEach(function(array) {
    array.forEach(function(arrayItem) {
      dataPoints.push({
        y: new Date(arrayItem.source_ts),
        x: Number(arrayItem.renewablesobligationconsumption)
      });
    });
  });

Below is a complete working example. Once your dataPoints are populated, you can use them as needed:

// Fetching the data
fetch('https://example.com/my/endpoint').then(response => {
  return response.json();
}).then(data => {

  // Generating Data Points
  var dataPoints = [];

  data.forEach(function(array) {
    array.forEach(function(arrayItem) {
      dataPoints.push({
        y: new Date(arrayItem.source_ts),
        x: Number(arrayItem.xyzw)
      });
    });
  });
  
 console.log(dataPoints);

  var chart = new CanvasJS.Chart("chartContainer", {
    data: [{
      dataPoints: dataPoints,
      type: "line",
    }]
  });

  chart.render();
}).catch(err => {
  throw new Error('Failed to fetch data');
});
<br/>
<!-- To prevent JSFiddle's Result label from overlapping the Chart -->

<div id="chartContainer" style="height: 300px; width: 100%;"></div>

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

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

Storing Data in an Array Using MongoDB's $push Method Depending on a Variable's Value

I'm attempting to add an item to my MongoDB record in Node (using MongoJS) by using the $push method. Here is an example of how it's done: exports.saveToUser = function (req, res) { console.log("IN"); var user = req.params.user; var ...

Typescript's tree-pruning strategy design for optimization

I've been working on developing a library that enforces the use of specific strategies for each target. The current structure I have in place is as follows: [Application] -> contains -> [player] -> contains -> [renderer] In the current s ...

Choose to either check or uncheck boxes using ReactJS

After successfully creating a function to select either single or multiple boxes, I encountered an issue with the "Select all" feature. Any suggestions on how to resolve this? (I'm utilizing the material-ui library for my checkboxes, which are essenti ...

Using Python, loop through a JSON file to extract particular attribute values

Here is the content of a json file: [ { "contributors": null, "coordinates": null, "created_at": "Fri Aug 04 21:12:59 +0000 2017", "entities": { "hashtags": [ { "indices": [ 32, ...

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 ...

The HTML form submission button fails to submit the form and instead just refreshes the page

I'm struggling to get the save button working on my Chrome Extension settings page. The .click() event doesn't seem to be activating at all. I've included my code below. Should I use the commented out button instead (see below)? HTML <! ...

Struggling to adjust the timeout to exceed 60 seconds

I have been attempting to set a timeout for 120 seconds or more, but no matter what I try, the requests are timing out after only 60 seconds. Things I have tried include: $.ajax({ url: URL, timeout: 120000, success: function(html){ co ...

I'm encountering a status 415 error when trying to post to the Spotify API for tokens. Is there something I'm

My approach to interfacing with their API for the Authorization Code Flow is as follows: class func obtainAuthTokenPackage(authCode: String) throws { //Initiate a request var request = URLRequest(url: Gimme.theSpotify.urlFor(endpoint: .requestingT ...

Creating an interactive quiz using JSON and distributing the results from a SQL query into a multidimensional array

Working on a quiz system that stores questions and answers in a MySQL database has led me to try and convert the data into a multidimensional array and then into JSON format. However, the result is not meeting my expectations and I'm stuck with the cu ...

What is the significance of static in react?

export class NavMenu extends Component { static displayName = NavMenu.name; constructor (props) { super(props); this.toggleNavbar = this.toggleNavbar.bind(this); this.state = { collapsed: true }; } I attempted to research the ...

Preventing the dispatch function from being overwritten by an empty state

Scenario: I am currently exploring the concept of React/Redux and aiming to understand the data flow. The process involves axios dispatching actions -> reducers setting state to props -> Component rendering. As a newcomer to the Frontend world, ...

Steps to configure caching settings to ensure no caching for the entire site during specific hours, and constant no-cache policy for a particular page

Managing cache for my website has become quite the challenge. Some pages need to be cached during certain hours to improve navigation speed, while others must not be cached during crucial data update times. And to add to the complexity, there are pages tha ...

Repeatedly Triggered JQuery AJAX Calls

On my web page, I have implemented a feature that allows users to search for an address using a GIS server's web-service. This functionality is triggered by a button click event which calls a JQuery AJAX method. Upon successful retrieval of address da ...

Converting a PHP array to JSON in the specific format that is needed

I am looking to create a PHP array by fetching data from a MySQL query and then convert it into JSON using a loop. The SQL query I am using looks like this: $arDados = array(); $result = $conexao->sql("SELECT * FROM sys_fabrica WHERE fl_ativo = 1 ORDER ...

Node.js encountered an error due to a self-signed certificate within the certificate chain

I'm encountering an issue with client-side HTTPS requests. An example snippet is as follows: var fs = require('fs'); var https = require('https'); var options = { hostname: 'example.com', port: 443, path: & ...

Hide popup in React Semantic UI when clicking on a different popup

I've integrated React Semantic UI into my application and I'm using the semantic Popup component to display tooltips. One issue I'm encountering is that when I click on a popup button, previously opened popups are not automatically closing. ...

Managing the Response from an Ajax Call

Currently, I am in the process of developing a user registration form for my website and have implemented ajax to manage server-side processes. My main issue lies in effectively handling the response generated by my PHP code. The potential responses from t ...

Using HTML and JavaScript to implement a dragging functionality on a canvas element

After creating a square grid using HTML canvas, I've added a drag feature that allows users to draw rectangles by dragging over the grid. However, it seems that non-rectangle shapes can also be drawn in certain cases. Let's delve into an additio ...

"Validation with Express-validator now includes checking the field in cookies instead of the request

My current validator is set up like this: const validationSchema = checkSchema({ 'applicant.name': { exists: true, errorMessage: 'Name field is required', }, }); and at the beginning of this route (the rest is not relevant) ...