Help, generate graphics with json

Asked

Viewed 207 times

-2

I need to generate a pie cart chart using js and json, I have the json file with the name of the courses and number of approved courses per course, I need js to read this information and generate the graph with them "I cannot generate the example graph: read the json and process the data so that it shows in the graph automatically. I want the names of the Courses and the approved numbers that are in json to fill in the required fields and generate the charts."

var nome_course;
var aprovados;

$(document).ready(function () {
$.getJSON("./report/report_curso.json", function (json) {

let nome_curso = json["nome_curso"];
let aprovados = json["matriculados"];

});
});


Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system- 
ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#858796';

// Pie Chart Example
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: [nome_curso],
datasets: [{
  data: [aprovados],
  backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
  hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
  hoverBorderColor: "rgba(234, 236, 244, 1)",
  }],
  },
  options: {
   maintainAspectRatio: false,
   tooltips: {
  backgroundColor: "rgb(255,255,255)",
  bodyFontColor: "#858796",
  borderColor: '#dddfeb',
  borderWidth: 1,
  xPadding: 15,
  yPadding: 15,
  displayColors: false,
  caretPadding: 10,
  },
   legend: {

  display: false
   },
   cutoutPercentage: 80,
   },
   });

inserir a descrição da imagem aqui

Json: [{"course name":"course 1","enrolled":"673"},{"course name":"course 2","enrolled":"906"},{"course name":"course 3","enrolled":"489"}]

  • What would be the problem ?

  • I cannot generate the example graph: read the json and process the data so that it shows in the graph automatically. I want the names of the Courses and the approved numbers that are in json to fill in the required fields and generate the charts.

  • You want to use the query result getJSON on the chart is this ?

  • To read a json you need to use Javascript methods for either map() or foreach() for example, if you still know how to play with such tools I believe you are not yet prepared to play with graphics.

  • yes that even in the case of the chart there where is "Labels:" would be inserted the name of the courses in EX format: ["course name 1","course name 2"]. And where is "date:" the number of those enrolled in the EX format:["673","906"]

  • I can also work with foreach(), but very little, so I came to ask for help, some light so that I can do what I need.

Show 1 more comment

1 answer

0


First of all it is necessary to remember some things.

  • We have to remember that the JS is synchronous, that is, he does not expect your consultation ajax for after generating the graph, it will do it all at once, it may be that in some cases the query is instantaneous, can assign the value to the variable, but this is a huge risk.
  • To facilitate use a json return based on this logic

    { 
        "matriculados": ["673", "906", "489"], 
        "nome_curso": ["Curso 1", "Curso 2", "Curso 3"] 
    } 
    

What would be the solution to the problem?

Solution 1

  • Create the chart within your query ajax, so after the query it will be possible to use the values of the graph without any problem, getting something like this:

    $.getJSON("./report/report_curso.json", function (json) {
        var ctx = document.getElementById("myPieChart");
        var myPieChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: json.nome_curso,
                datasets: [{
                    data: json.matriculados,
                    backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
                    hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
                    hoverBorderColor: "rgba(234, 236, 244, 1)",
                }],
            }
        });
    });
    

Solution 2

  • Make your function asynchronous, that is, make it obligatory, before creating the chart is necessary to wait for the return of the query ajax , getting something like this:

    const createGraph = async () => {
        let nome_curso = [];
        let matriculados = [];
    
        $.getJSON("./report/report_curso.json", function (json) {
    
            nome_curso = json.nome_curso;
            matriculados = json.matriculados;
    
        });
    
        var ctx = document.getElementById("myPieChart");
        var myPieChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: [nome_curso],
                datasets: [{
                    data: [matriculados],
                    backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
                    hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
                    hoverBorderColor: "rgba(234, 236, 244, 1)",
                }],
            }
        });
    }
    

Solution 3

  • If you wanted to continue using the format json as announced, can carry out the logic of the consultation ajax thus:

    $.getJSON("./report/report_curso.json", function (json) {
    
        let cursos_json = [];
        let matriculados_json = [];
    
        for (let index = 0; index < json.length; index++) {
            cursos_json.push(json[index].nome_curso); // add nome do curso no array
            matriculados_json.push(json[index].matriculados);  // add matricula no array
        }
    
    })
    

References:

Chartjs

Asynchronous functions

  • I understood everything right the problem is that my json is automatically generated from elsewhere, so it comes in the format I passed :(

  • I edited the answer, just use this logic in the query ajax and assignment of variables.

  • gave it right, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.