简体   繁体   English

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

[英]Chart.js using the value of certain data in external json file

I'm working on this self exploration which I want to show a chart that shows how many anime that have comedy genre or fantasy genre.我正在做这个自我探索,我想展示一个图表,显示有多少动漫有喜剧类型或幻想类型。 The data for my chart is going to be an external json file (anime.json) on my computer and it's not yet contain the total of how many anime that have comedy or fantasy genre, so I need to do some loop to know that.我的图表数据将是我计算机上的外部 json 文件 (anime.json),它尚未包含喜剧或奇幻类型动漫的总数,因此我需要进行一些循环才能知道这一点。 I try this to make it happen by trying with this code:我尝试通过使用以下代码来实现它:

<!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>

But when I open this html on my browser, It came up empty so I'm wondering what is the correct way to do it.但是当我在浏览器上打开这个 html 时,它是空的,所以我想知道正确的方法是什么。 And this is my json file (and I have like 25 or 30 of them):这是我的 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"
    ]
}]

Thank you!谢谢!

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.您在$.getJSON之后编写的代码应该放在回调函数中。 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.如果您打开console您可能会看到错误,因为最初cannot read property length of 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM