Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

321
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda