You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何整合Mustache模板读取JSON数据并在Chart.js中动态生成柱状图?

问题:Mustache传递数据生成Chart.js柱状图失败

尝试将data.json中的数据通过Mustache模板传递以创建柱状图,但无法确定正确的数据传递位置,导致图表无法正常生成。以下是相关代码及报错信息:

HTML代码

<html>
<body>
<div>
    <canvas height="200px" width="300px" id="bar-graph"></canvas>
</div>

<script>
     const barCtx = document.getElementById('bar-graph').getContext('2d');
     new Chart(barCtx, barGraphConfig());
     function barGraphConfig() {    
    return {
      type: 'bar',
      data: {
        datasets: [{
          data: {{barGraph}},
          borderRadius: 5,
          backgroundColor: [
            '#fece8c',
            '#a28cfe',
            '#a28cfe',
            '#feab8c',
            '#8ca2fe',
            '#8ca2fe',
          ],
          barThickness: 20
        }],
        labels: ['AAA', 'AA', 'A', 'BBB', 'BB', 'B']
      },
      options: {
        plugins: { legend: { display: false } },
        showTooltip: false,
        animation: {
          duration: 0,
          onComplete: renderDataLabel,
        },
        parsing: {
          xAxisKey: 'sector',
          yAxisKey: 'value'
        },
        scales: {
          x: {
            grid: {
              borderWidth: 3,
              borderColor: '#232323',
              display: false,
            },
          },
          y: {
            display: false,
            beginAtZero: true
          }
        }
      },
    };
  }
</script>
</body>
</html>

原始data.json(非标准格式)

barGraph: [
  {
    "name": "A",
    "value": 4
  },
  {
    "name": "AAA",
    "value": 10
  },
  {
    "name": "B",
    "value": 40
  },
  {
    "name": "BB",
    "value": 20
  },
  {
    "name": "BBB",
    "value": 7
  }
]

报错截图

报错截图


问题排查与修复

核心问题点

  1. data.json格式不合法:原始内容不是标准JSON,缺少外层对象包裹,键名未加双引号,Mustache无法正确解析。
  2. Chart.js解析配置与数据字段不匹配:parsing.xAxisKey设为'sector',但数据中对应的字段是'name',无法映射x轴标签。
  3. 数据顺序与labels数组不一致:labels顺序为['AAA', 'AA', 'A', 'BBB', 'BB', 'B'],但原始数据顺序混乱,导致柱子与标签错位;且缺少AA对应的数据,会出现柱子缺失。
  4. Mustache渲染时机错误:JS代码在DOM与模板未完全渲染时执行,{{barGraph}}未被解析为合法JS数组,触发语法错误。

修复方案

1. 修正data.json为标准JSON格式

{
  "barGraph": [
    {"name": "AAA", "value": 10},
    {"name": "AA", "value": 0},
    {"name": "A", "value": 4},
    {"name": "BBB", "value": 7},
    {"name": "BB", "value": 20},
    {"name": "B", "value": 40}
  ]
}

(补充AA的数值0,保证与labels长度一致;调整顺序匹配labels数组)

2. 调整HTML中的Chart.js配置与执行时机

<html>
<body>
<div>
    <canvas height="200px" width="300px" id="bar-graph"></canvas>
</div>

<script>
     // 等待DOM与Mustache模板渲染完成后执行
     document.addEventListener('DOMContentLoaded', function() {
       const barCtx = document.getElementById('bar-graph').getContext('2d');
       new Chart(barCtx, barGraphConfig());
     });
     
     function barGraphConfig() {    
    return {
      type: 'bar',
      data: {
        datasets: [{
          data: {{barGraph}},
          borderRadius: 5,
          backgroundColor: [
            '#fece8c',
            '#a28cfe',
            '#a28cfe',
            '#feab8c',
            '#8ca2fe',
            '#8ca2fe',
          ],
          barThickness: 20
        }],
        labels: ['AAA', 'AA', 'A', 'BBB', 'BB', 'B']
        // 可选:从数据动态生成labels,避免顺序不一致问题
        // labels: {{barGraph}}.map(item => item.name)
      },
      options: {
        plugins: { legend: { display: false } },
        showTooltip: false,
        animation: {
          duration: 0,
          onComplete: renderDataLabel,
        },
        parsing: {
          // 匹配数据中的字段名name
          xAxisKey: 'name',
          yAxisKey: 'value'
        },
        scales: {
          x: {
            grid: {
              borderWidth: 3,
              borderColor: '#232323',
              display: false,
            },
          },
          y: {
            display: false,
            beginAtZero: true
          }
        }
      },
    };
  }
</script>
</body>
</html>

内容的提问来源于stack exchange,提问作者SrinivasN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:10:31