Retrieve information from json, divide it, and transfer it to the chart for display

Greetings everyone! In my project, I am parsing a JSON file from an online API. However, I have encountered a roadblock while trying to split the data. Despite searching extensively on platforms like YouTube, I haven't been able to find a solution that fits my needs. As a newcomer to JavaScript, I am struggling with this task. The structure of the JSON file looks like this:

"timeline": {
"cases": {
"8/29/21": 1874435,
"8/30/21": 1881213,
"8/31/21": 1888150,
"9/1/21": 1895459,
"9/2/21": 1902407,

My goal is to visualize this data in a chart.

For creating charts, I am using ApexCharts. Here is a snippet of my code:

 
    dayno = 30; 
url = "https://disease.sh/v3/covid-19/historical/iraq?lastdays=" + dayno; 
var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};
// .then(result => console.log(result.timeline.cases)
const {cases}= timeline;
fetch(url, requestOptions)
  .then(response => response.json())
  .then(result => console.log(result.timeline.cases))
 
  .then(result => console.log(result))
  .catch(error => console.log('error', error));


  var options = {
    chart: {
      height: 280,
      type: "area"
    },
    dataLabels: {
      enabled: false
    },
    series: [
      {
        name: "Series 1",
        data: [45, 52, 38, 45, 19, 23, 2] // number of cases after split it
      }
    ],
    fill: {
      type: "gradient",
      gradient: {
        shadeIntensity: 1,
        opacityFrom: 0.7,
        opacityTo: 0.9,
        stops: [0, 90, 100]
      }
    },
    xaxis: {
      categories: [
        "01 Jan", // date here from split 
        "02 Jan",
        "03 Jan",
        "04 Jan",
        "05 Jan",
        "06 Jan",
        "07 Jan"
      ]
    }
  };
  
  var chart = new ApexCharts(document.querySelector("#chart"), options);
  
  chart.render();

Answer №1

Avoid using categories in the xaxis for simple date charts.

Instead, it is recommended to specify type: "datetime".

xaxis : { type: 'datetime' }

When fetching data, make sure to format it accordingly.

fetch(url, requestOptions)
  .then(response => response.json())
  .then(result => {
  let tempSerie = {name: 'cases', data: []}
  for (const [key, value] of Object.entries(result.cases)) {
  tempSerie.data.push([key, value]);
  }
  chart.updateSeries([tempSerie]);
  })
  .catch(error => console.log('error', error));

Create a temporary series variable to store an object with the name cases and an empty data array.

Iterate through the object properties and push a new [key, value] array to the data array.

Finally, update the chart series accordingly.

Answer №2

I have made some changes to your code below. Kindly review and see if it resolves the issue. You can utilize javascript Object.keys to fetch the keys of objects and Object.values to retrieve the values of the JSON object.

dayno = 30; 
url = "https://disease.sh/v3/covid-19/historical/iraq?lastdays=" + dayno; 
var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};
// .then(result => console.log(result.timeline.cases)
const {cases}= timeline;

fetch(url, requestOptions)
  .then(response => response.json())
  .then(result => console.log(result.timeline.cases))
 
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

const series1 = Object.values(cases);
const dates = Object.keys(cases);

  var options = {
    chart: {
      height: 280,
      type: "area"
    },
    dataLabels: {
      enabled: false
    },
    series: [
      {
        name: "Series 1",
        data: series1 // number of cases after split it
      }
    ],
    fill: {
      type: "gradient",
      gradient: {
        shadeIntensity: 1,
        opacityFrom: 0.7,
        opacityTo: 0.9,
        stops: [0, 90, 100]
      }
    },
    xaxis: {  
      categories: dates // date her form split
    }
  };
  
  var chart = new ApexCharts(document.querySelector("#chart"), options);
  
  chart.render();

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 to Resolve ENOENT ERROR When Using fs.unlink in an Express.js Simple Application?

Currently, I am developing a basic blog using express.js. For managing the posts, I have opted for Typicode/lowdb as my database. The posts are created, updated, and deleted based on unique IDs stored in a data.json file. Additionally, I utilize the slug d ...

Utilizing JSON in a d3.js application within a Rails environment

I have been exploring the gem gon in order to generate JSON data from my Rails database. I have successfully managed to display this data in an alert, but now I am looking to visualize it using d3.js. Within my database named "users" with columns (name:st ...

Getting the parameter route value from Laravel and passing it to Ajax

Need help with returning the parameter of a Laravel route to an AJAX response. Here is the relevant code: public function getPermissions(Request $request) { //$v = request()->route()->parameters('profile'); $v = request()-& ...

The Spring API is recommended to output JSON data instead of returning an escaped String

I need to configure my Spring endpoint to return JSON without escaping double quotes so it can be collapsed/expanded in Chrome. Is there a way to specify to Spring that the string in the message is actual JSON representation? Here is the declaration of th ...

Updating new objects in Angular using JavaScript Object-Oriented Programming may not be working

Recently delving into OOP in JavaScript while working on an AngularJS website, I encountered a situation where my object methods were only altering the properties within the class, but not affecting the new object itself. //Class Var Item = function() { ...

Parse the JSON object from the request when the content type is set to 'application/x-www-form-urlencoded'

I have an integration with a payment service, and they sent me a request using cURL like this: curl -d '{"merchantAccount":"pipedrive_youscore_rubicon_ltd","orderReference":"WFP-BTN-7181819-635e48482b33d"," ...

Displaying each character of text individually with jQuery

I am trying to display the text within a ul tag one by one when hovering over some text. However, I am encountering an error. How can I resolve this issue? You can view the code for mouseover functionality by hovering over the "hover here hover again" lin ...

How do you incorporate ScrollTop animations using @angular/animations?

I'm attempting to recreate the animation showcased on Material.io: https://i.stack.imgur.com/OUTdL.gif It's relatively easy to animate just the height when clicking on the first card in the example above. The challenge arises when you click on ...

Question about sending multiple Axios POST requests with parameters

I'm new to Stack Overflow and seeking help with a specific issue on my Rails backend and Vue.js frontend website. The challenge I'm facing involves making two POST requests simultaneously when the submit button is clicked. My "Trips" controller ...

How come I am receiving a null value for isMatch from bcrypt compare even though the two password strings match exactly?

Currently, I am attempting to authenticate a user based on a password. My approach involves using bcrypt compare to check if the user's requested password matches one stored in a MongoDB database. Despite the passwords being identical, I keep receivin ...

Interactive Google Maps using Autocomplete Search Bar

How can I create a dynamic Google map based on Autocomplete Input? Here is the code that I have written: <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDeAtURNzEX26_mLTUlFXYEWW11ZdlYECM&libraries=places&language=en"></scri ...

What is the best way to invoke my Python function within my JavaScript file?

I am facing an issue with using my Python function in JavaScript. Although the actual code I am working on is more complex, I have simplified it to demonstrate the problem below: main.mjs dbutils.notebook.run("./aPythonFile.py", 5, {"parame ...

How to dynamically display a div in Vue.js depending on the attributes of another element

I have a dilemma with my text container. My goal is to collapse the div if the text length exceeds a certain limit, and then display a button that says "...show more". When this button is clicked, the div should expand. Clicking it again should collapse th ...

The submission of an Angular form results in errors such as being unavailable or

After building a registration page component in Angular and following tutorials, I encountered a frustrating bug. When pressing the submit button on the form, the console would display "undefined" when attempting to access the NgForm's value. However, ...

Unable to get Discord.js sample code functioning correctly

Despite my best efforts, I can't seem to figure out why this simple example code is not working. As a newcomer to Java Script, I am struggling with understanding why the line GatewayIntentBits.Guilds is causing an error. Surprisingly, when I comment o ...

What is the best way to retrieve the ID of a post request using React's axios hook?

My goal is to make a post request to create an app, and then establish its links. To achieve this, I need to obtain the id of the newly created items in order to create the links. Is there a way to retrieve the id of the item created through the post reque ...

Facing compatibility problems with JavaScript and Cascading Style Sheets in Google Chrome?

Welcome to the site . Let's address a couple of issues with JavaScript and CSS: Firstly, the JS code seems to be malfunctioning only in Chrome, throwing an error that reads: 'Uncaught TypeError: Object [object Object] has no method 'on prij ...

The variable 'firebase' is nowhere to be found

I am encountering an issue with the error message 'Can't find variable: firebase' and I am struggling to identify the cause of this error. I have installed firebase using 'yarn add firebase' and double-checked that it is properly i ...

What Causes the "Not a String or Buffer Type" Unhandled Exception?

I've encountered an error that seems to be originating from the following line of code, even though I believe I am following the example correctly (viewable at https://www.npmjs.org/package/aws-sign). Any help or hints would be greatly appreciated. v ...

Reading Json information in flutter

Hey there, I'm working with a JSON file and trying to display the data on the screen. However, nothing is showing up, and I suspect it might be due to an issue with my implementation. class TestScreen extends StatefulWidget { const TestScreen({Key? ...