Chartjs-Chart.js using the value of certain data in external json file

0👍

Your code seems to be fine, the only thing I can see is you are not handling the callback properly. The code you have written after $.getJSON should be placed inside the callback function. As because of the async behavior your data is set after other codes are executed. If you open console you may see error as cannot read property length of undefined as initially, the data is undefined.

Below snippet should fix your problem.

<script>
$.getJSON("anime.json", function (json) {
  const data = json;
  let comedy = 0;
  let fantasy = 0;
  for (i = 0; i < data.length; i++) {
    let genres = data[i]["genres"];
    for (j = 0; j < genress.length; j++) {
      let value = genres[j].trim();
      if (value.toLowerCase() == "comedy") {
        comedy = comedy + 1;
      }
      if (value.toLowerCase() == "fantasy") {
        fantasy = fantasy + 1;
      }
    }
  }

  let myChart = document.getElementById("myChart").getContext("2d");

  let massPopChart = new Chart(myChart, {
    type: "bar",
    data: {
      labels: ["Comedy", "Super Natural"],
      datasets: [
        {
          label: "Genre",
          data: [comedy, superNatural],
        },
      ],
    },
    options: {},
  });
});
</script>

Leave a comment