Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

325
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda