Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

320
Views
How to get data of json file for chart.js diagram

I want to read a .json file and use its data for the data attribute of a chart.js diagram.

My code is as follows:

const test = []

fetch("./load.json")
.then(response => {
   return response.json();
})
.then(data => {
    // console.log(data)
    for (i = 0; i < data.length; i++) {
        // console.log(data[i])
        test.push(data[i])
    }
});

console.log(test)

// setup block
const data = {
        datasets: [{
            label: 'Sales',
            data: test,
            borderColor: 'rgba(234,124,234,0.4)',
            backgroundColor: 'rgba(34,14,24,0.4)'
        }]
};
// config block
const config = {
    type: 'line',
    data,
    options: {
        scales: {
            x: {
                type: 'time',
                time: {
                    unit: 'second'
                }
            },
            y: {
                beginAtZero: true
            },
            xAxes: [{
                type: "time",
                time: {
                    min: 1628373600,
                    max: 1628460000
                }
            }]
        }
    }
};
// render / init block
const myChart = new Chart(
    document.getElementById('myChart'),
    config
);

My .json file:

[{"x": "2021-08-08T13:12:23", "y":3},
    {"x": "2021-08-08T13:12:45", "y":5},
    {"x": "2021-08-08T13:12:46", "y":6},
    {"x": "2021-08-08T13:13:11", "y":3},
    {"x": "2021-08-08T13:14:23", "y":9},
    {"x": "2021-08-08T13:16:45", "y":1}]

I have tried to parse the data from the .json file and in console it shows up but I think the data attribute of chart.js is not able to read the data in the test variable.

Does somebody know how to do this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Seems like the chart is being made before the data is ready since loading the json is an async proces, you can either instantiate the chart in your second .then when the data is available or create the chart as you do and then in the second .then update the data in the chart and call the update method

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!