Chart.js使用外部json文件中的某些数据的值

问题描述 投票:0回答:1

我正在进行自我探索,我想显示一张图表,该图表显示有喜剧类型或幻想类型的动漫。我图表的数据将是我计算机上的一个外部json文件(anime.json),尚未包含具有喜剧或幻想类型的动漫总数,因此我需要做一些循环才能知道这一点。我尝试通过使用以下代码来实现这一目标:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <canvas id="myChart"></canvas>
</div>

<script>
    let data;
    $.getJSON("anime.json", function(json){
            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>
</body>
</html>

但是当我在浏览器中打开此html时,它变成空的,所以我想知道什么是正确的方法。这是我的json文件(我有25或30个):

[
{
    "cover_title": "Haikyuu!! TO THE TOP",
    "cover_studio": "Production I.G",
    "cover_img": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx106625-UR22wB2NuNVi.png",
    "format": "TV",
    "duration": "84%",
    "description": "The fourth season of Haikyuu!!\n\nThe Karasuno High School Volleyball Club finally won their way into the nationals after an intense battle for the Miyagi Prefecture Spring Tournament qualifiers. As they were preparing for the nationals, Kageyama is invited to go to All-Japan Youth Training Camp. At the same time, Tsukishima is invited to go to a special rookie select training camp for first-years in Miyagi Prefecture. Hinata feels panic that he\u2019s being left behind as one of the first-years and then decides to show up at the Miyagi Prefecture rookie select training camp anyway...\n\n(Source: Crunchyroll)",
    "genres": [
        "Comedy ",
        " Drama ",
        " Sports"
    ]
},
{
    "cover_title": "Eizouken ni wa Te wo Dasu na!",
    "cover_studio": "Science SARU",
    "cover_img": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx109298-YvjfI88hX76T.png",
    "format": "TV",
    "duration": "79%",
    "description": "First year high schooler Midori Asakusa loves anime so much, she insists that \"concept is everything\" in animation. Though she draws a variety of ideas in her sketchbook, she hasn't taken the first step to creating anime, insisting that she can't do it alone. The producer-type Sayaka Kanamori is the first to notice Asakusa's genius. Then, when it becomes clear that their classmate, charismatic fashion model Tsubame Mizusaki, really wants to be an animator, they create an animation club to realize the \"ultimate world\" that exists in their minds.\n\n(Source: Crunchyroll)",
    "genres": [
        "Adventure ",
        " Comedy"
    ]
},
{
    "cover_title": "Made in Abyss: Fukaki Tamashii no Reimei",
    "cover_studio": "Kinema Citrus",
    "cover_img": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx100643-fPH9OgEKKvcI.jpg",
    "format": "Movie",
    "duration": "78%",
    "description": "Dawn of the Deep Soul continues the epic adventure of plucky Riko and Reg who are joined by their new friend Nanachi. Together they descend into the Abyss\u2019 treacherous fifth layer, the Sea of Corpses, and encounter the mysterious Bondrewd, a legendary White Whistle whose shadow looms over Nanachi\u2019s troubled past. Bondrewd is ingratiatingly hospitable, but the brave adventurers know things are not always as they seem in the enigmatic Abyss...\n\n(Source: Sentai Filmworks)",
    "genres": [
        "Adventure ",
        " Fantasy ",
        " Sci-Fi ",
        " Drama"
    ]
}]

谢谢!

javascript html json chart.js
1个回答
0
投票

您的代码似乎很好,我唯一能看到的是您没有正确处理回调。在$.getJSON之后编写的代码应放在回调函数中。由于异步行为,您的数据将在执行其他代码后设置。如果打开console,可能会像最初一样显示为cannot read property length of undefined的错误,该数据是未定义的。

下面的代码段应该可以解决您的问题。

<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>
© www.soinside.com 2019 - 2024. All rights reserved.