Utilizing amCharts Postprocessing for fetching data for visual representation

My goal is to utilize amcharts for displaying data retrieved from my server. Unfortunately, the API format doesn't align directly with amCharts. It seems that I need to utilize the postProcess function to preprocess the data, but I am struggling due to the lack of error messages and my limited experience in javascript.

Following their instructions, here is where I currently stand:

var chart = AmCharts.makeChart( "$CHART$", {
  "type": "serial",
  "legend": {
    "horizontalGap": 10,
    "maxColumns": 1,
    "position": "right",
    "useGraphSettings": true,
    "markerSize": 10
  },
"dataLoader": {
    "format": "json",
    "postProcess": function( data, config, chart ) {
    var newData = [];
    for ( var i = 0; i < data.rows.length; i++ ) {
      var dataPoint = {};
      dataPoint= data["items"];
      
      newData.push( dataPoint );
    }
    return newData;
  },
    "showCurtain": true,
    "showErrors": true,
    "url": "*url*",
    "headers": [{
    "key": "Accept",
    "value": "application/javascript, application/json",
    "Authorization":"Basic *encodedpassword*"
  }]
    
  },  "categoryField": "timestamp",
  "graphs": [  {
    "valueField": "value",
    "bullet": "round",
    "bulletBorderColor": "#6698FF",
    "bulletBorderThickness": 2,
    "bulletAlpha":0,
    "bulletSize":0,
    "title":"ServerData",
    "lineThickness": 2,
    "lineColor": "#6698FF",
    "lineAlpha": 0.5,
    "fillAlphas": 0.8,
    "fillColors":"#6698FF",
  } ],
  "valueAxes": [{
        "axisAlpha": 0,
        "dashLength": 5,
        "gridCount": 10,
        "position": "left",
    "unit": "V",
    }],
  "categoryAxis": {
    "minPeriod": "mm",
    "labelsEnabled": false
  },
  "chartCursor": {
    "oneBalloonOnly": true,
    "zoomable":true
  },
} );

The sample output returned from the server's API is provided below:

{"href":"*url/value*","offset":0,"limit":20,"items":[
{"stateVarId":"value1","timestamp":1523939135978,"value":887.0},
{"stateVarId":"value1","timestamp":1523935535977,"value":887.0},{"stateVarId":"value1","timestamp":1523845535955,"value":887.0}]}

In order for amCharts to interpret the values correctly, they should not be nested inside the "items":[ ...] section.

Therefore, the postProcess function must navigate the JSON format and extract the contents of "items".

If you require additional information, please feel free to reach out. I will gladly provide any missing details.

Thank you.

Answer №1

The issue with your postProcess method lies in how you are handling the array of items. Instead of creating an array of arrays, you should be creating a flattened array. Here's a breakdown of what's going wrong in your loop for each row of data:

  var dataPoint = {};
  dataPoint = data["items"]; // dataPoint is now an array

  // This line pushes the array as an element of newData, resulting in
  // [ [/*first items array*], [/*second items array*], ...]
  newData.push(dataPoint); 

What you should be doing instead is looping through the data["items"] array and pushing each element individually into your newData array, or using Array.concat to accomplish this:

  // Concatenates the existing newData array
  // with the next data["items"] array
  newData = newData.concat(data["items"]); 

On a side note, if you are working with date/timestamp-based data and utilizing parseDates, it is essential for the data to be in ascending order. This is crucial for features like minPeriod to function properly. Your sample API response shows items sorted in descending timestamp order, so remember to sort newData before returning it in postProcess.

Answer №2

After my conversation with the team at Chartify, they provided me with the following solution:

"transformData": function( data, settings, chart ) {
var transformedData = [];
for ( var i = 0; i < data.entries.length; i++ ) {
  var newDataPoint = {};
  newDataPoint= data.entries[i];
  transformedData.push( newDataPoint );
}
return transformedData;
},

However, I later discovered that the reason it wasn't working on my site was due to a CORS error.

Appreciate the help of everyone who took the time to read my question. =)

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

Using val() on a checkbox will give you an element, not a string literal

How can I retrieve only the literal values of all checked checkboxes without any additional data? My current approach is: $('input:checked').map(function() { return $(this).val(); }) The result that I am getting looks like this: e.fn.init[1]0 ...

Replace Vue's mixin function

Is it possible to overwrite one of npm's mixins that is used within a component with a local mixin? I have a component from an npm package located in node_modules/somePackageName/components/footer.vue which uses a mixin from node_modules/somePackageN ...

Creating a user-friendly form with validation in a Vue application using Vuetify.js

I am in the process of incorporating a contact form with basic validation on a Vue.js website using an example from Vuetify.js. Being new to this, I'm unsure about how to implement it within a Vue component. My goal is to have simple client-side form ...

Adjust the placement of the fixed header waypoint or change its offset

Currently working on developing a Wordpress site with the Avada theme, my goal is to have a sticky header that starts immediately at the top of the page. This is the website in progress: The site I'm trying to emulate is synergymaids.com. If you vi ...

Transmit an unmodifiable array using JSON and Ajax

Is there a way to transmit arrays in a non-editable format? The data I wish to transmit looks like this: var items = []; //console.log(JSON.stringify(items)); allitems = JSON.stringify(items); [{ "assetid": "7814010469", "classid": "1797256701", ...

Is Angular 4 failing to set headers properly or is Express.js searching in the wrong place?

When interacting with an Express.js API, I encountered a issue regarding the handling of auth tokens. The problem arose when sending the token in the request headers using Angular 4 compared to Postman. In Postman, setting the header named 'Authorizat ...

"Exploring the intricacies of routing within a Node.js application

I previously had around 100 blogs displayed on the "/" page with links for sorting by date (a-z). When clicking on these links, I am redirected to different routes - one is "/sort_by_date" and the other is "/sort_alphabetically". Unfortunately, I was unabl ...

Preventing blank text entries in a task management application

Is there a way to determine if the text input provided by the user is empty or contains some text? I'm in the process of developing a TO-DO app and I'd like it so that if a user fails to enter anything into the text area and clicks on "add", the ...

Discover particular key value pairs using jq

Below is a snippet of JSON data where filtering for records with a null charge can be achieved using the command jq -M ' map(select(.charge == null)) ' [ { "id": 1, "name": "vehicleA", "state": "available", "charge" ...

PHP's json_encode() compared to using an empty NSDictionary in iOS development

I have a question regarding how to handle JSON encoding/decoding in PHP without converting arrays or dictionaries. In my iOS app, I store data in an NSDictionary. Some of this data is nested and includes NSArrays or other NSDictionarys that may contain fu ...

A declaration file in Typescript does not act as a module

Attempting to create a TypeScript declaration file for a given JavaScript library my_lib.js : function sum(a, b) { return a + b; } function difference(a, b) { return a - b; } module.exports = { sum: sum, difference: difference } my_lib.d.ts ...

Error: No package.json file found after publishing npm package with ENOLOCAL

Ecosystem using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="335d435e73051d021d03">[email protected]</a> using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a8a9a2a386b0fee8f7f7e ...

Concerns with the performance of Leaflet's polyline

Currently using Leaflet version 1.0.3 and encountering an issue with GPS positions on my map. Within a for loop, I am creating circle markers for each GPS position: var position = new L.latLng(lat, lng); coordinates.push(position); L.circle([lat, lng], ...

The checkValidity function fails to identify incorrect "tel" input

In my form, I am using the checkValidity function to validate inputs. However, I have encountered an issue where the validation only works when an input with the required attribute is missing a value. It doesn't work if there is a value type mismatch, ...

I am unable to sketch my backdrop. - HTML Canvas Game

Recently I've encountered an issue in my code where the image doesn't appear and mouse interaction stops working when I uncomment bg.draw() within the draw function. function draw() { clearAllCtx(); player.draw(); ene ...

Discover the process of accessing nested arrays in MongoDB

I am facing a challenge with retrieving patient_ids from nested json array where the code value is M18.1 using a mongo db query. {"zip":"04903","specialty":"cardiac","number_of_patients":250,"data":[{"gender":"male","age_data":[{"age":1,"diagnostic_dat ...

Extract information from JSON-formatted string

Currently, I am retrieving JSON data in Arduino using HTTP methods and storing it within a String object. The data structure is as follows: { "item": { "Identity": { "Id": "327681", "ItemId": "64006A962B71A1E7B3A0428637DA997C.327681", ...

Confirming Bootstrap - Implement an onConfirm method for element attributes

I am looking to add a JavaScript function to my confirmation button. I have created the elements off-page and fetched them using ajax, so it is crucial that I can set the function in-properties rather than via $('#id').confirmation() So far, I h ...

Utilizing JQuery and AJAX to fetch a specific variable

Hey there, I'm new to jQuery and AJAX. I've been attempting to pass a value from page 2 to page 1 using this script, but it doesn't seem to be working properly. Check out the script: function prova() { var parametro = $("#nome_priv ...

Issue: Encounter an Error with Status Code 401 using Axios in React.js

For my login page, I am utilizing a combination of Laravel API and ReactJS frontend. In my ReactJS code, I am using Axios to handle the parsing of the username (email) and password. The login API endpoint is specified as http://127.0.0.1:8000/api/login, wh ...