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

Password Field Validation in React

<TextField id="outlined-basic" label="Password" variant="outlined" /> Can anyone assist me in implementing password validation using an onchange function? I am seeking help with the ...

Error 405: Javascript page redirection leads to Method Not Allowed issue

After receiving the result from the ajax success method, I am facing an issue where the redirection to another page is being blocked and displaying the following error: Page 405 Method Not Allowed I am seeking suggestions on how to fix this as I need to ...

Accessing JSON data in Python

I have been attempting to fetch weather predictions from DarkSky using their API by executing the following code. I am specifically interested in the hourly forecasted data: url="https://api.darksky.net/forecast/api_key/33.972386,-84.231986" response = re ...

Navigating with nodeJS

Currently, I am in the process of learning how to create a Node.js project. My latest endeavor involved following a tutorial to develop a chat application. However, it seems like there is an issue with the routing between the server side and client side. ...

Efficiently Transmitting JSON Data via HTTP Requests

I have the following: Route file "prontuarios.js": module.exports = function(app){ getProntuarios = function(request, response, next){ var sqlCustom = request.query; var connection = app.infra.connectionFac ...

In order to effectively manage the output of these loaders, it may be necessary to incorporate an extra loader. This can be achieved by using the

I'm currently working with react typescript and trying to implement a time zone picker using a select component. I attempted to utilize the npm package react-timezone-select, but encountered some console errors: index.js:1 ./node_modules/react-timezo ...

I am having trouble getting two similar Javascript codes to function simultaneously

Using a common JavaScript code, I am able to display a div when a certain value is selected. http://jsfiddle.net/FvMYz/ $(function() { $('#craft').change(function(){ $('.colors').hide(); $('#' + $(this ...

Converting newline characters to valid JSON format in GO

I am facing a challenge converting strings to JSON due to the presence of special characters, such as newlines, which can disrupt the JSON format. While using encoding/json, I noticed that passing a string literal works fine as it automatically adds neces ...

Providing properties to the main Vue.js components

An Issue I'm Facing I am currently attempting to pass a prop to my root constructor. To achieve this, I have been exploring the use of propsData, which I learned about from this resource: var appComponent = Vue.component('app', require(&ap ...

JavaScript Scrolling Functionality Not Functioning as Expected

I have implemented a scroll function on my website $('#lisr').scroll( function() { if($(this).scrollTop() + $(this).innerHeight()>= $(this)[0].scrollHeight) { //Perform some action here } } However, I am encountering an ...

Contrasting results when logging an element in Chrome versus IE

Running the script below in Internet Explorer gives the expected output for console.log(target_el): <div class="hidden"></div> However, when run in Chrome, the output changes to: <div class="visible"></div> To add a humorous twi ...

Refresh the DOM based on changes in Vuex store state

One of the issues I'm facing is with an 'Add To Basket' button that triggers a Vuex store action: <button @click="addToBasket(item)" > Add To Basket </button> The Vuex store functionality looks like this: const actions = { ...

Execute a multer request to upload an image (using javascript and express)

I am utilizing the Express server as an API gateway for my microservices, specifically to process and store images in a database. The issue at hand is that within the Express server, I need to forward an image received through a POST request from the clien ...

Error with AngularJS: IE not showing dropdown options for MultiSelect

My application features a multiselect dropdown menu that shows a list of countries. While this dropdown functions correctly in Chrome, it displays options differently in IE as shown below: https://i.stack.imgur.com/xhOmV.png I have attempted to adjust th ...

What is causing my Li elements to be unchecked in REACT?

Why is the 'checked' value not changing in my list? I'm currently working on a toDo app Here are my State Values: const [newItem, setNewItem] = useState(""); const [toDos, setToDos] = useState([]); This is my function: funct ...

AngularJS restricts inputs to be read-only

I'm facing an issue with readonly inputs in AngularJS. I have a select element that changes the values of readonly inputs through a script. However, when I attempt to display these values using ng-model in a table as {{ng-model}}, they don't appe ...

` `issues with fmt:massage tag` `

When I try to update my page elements using ajax, I encountered a problem: the fmt:message tag doesn't work when I set it in javascript. In the JSP page everything works fine: <div id="div"> <fmt:message key="search_select_country"/> & ...

Leap over in a similar fashion to the provided demonstration

In my attempt to create a unique project, I have created this CodePen example. The goal is to have one ball on the circle that remains in a fixed position, while another rotating main ball must avoid touching it at all costs. Points are awarded for success ...

The information is not appearing in the dropdown menu

The select tag for chapters is not displaying the result from the query properly. Instead of showing in the select tag, the chapter names are being displayed as echo statements. <!doctype html> <html> <head> <meta charset="utf-8"> ...

What is the best way to convert a number into a string format for JSON formatting?

I am struggling with this code that I wrote to output data in JSON format for Google Chart. However, the issue I'm facing is that the return value for numbers is being converted into strings and cannot be read by Google Chart. $rows = array(); foreac ...