Chartjs-Opening json file to create chart in chart.js

0👍

Your issue in labels: data.date, if you try to check your json response you will see an array of items, so that you cant access date item else if you specify index of data like labels: data[0].date

Another issue
You are try to use Line chart from Chartjs, and I think you need to check how you can pass data like this url: Chartjs – Line (you are put data.mass direct too and its most be fetched)

var myLineChart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: options
});

for example:

new Chart(document.getElementById("line-chart"), {
  type: 'line',
  data: {
    labels: [1500,1600,1700,1750,1800,1850,1900,1950,1999,2050],
    datasets: [{ 
        data: [86,114,106,106,107,111,133,221,783,2478],
        label: "Africa",
        borderColor: "#3e95cd",
        fill: false
      }, { 
        data: [282,350,411,502,635,809,947,1402,3700,5267],
        label: "Asia",
        borderColor: "#8e5ea2",
        fill: false
      }, { 
        data: [168,170,178,190,203,276,408,547,675,734],
        label: "Europe",
        borderColor: "#3cba9f",
        fill: false
      }, { 
        data: [40,20,10,16,24,38,74,167,508,784],
        label: "Latin America",
        borderColor: "#e8c3b9",
        fill: false
      }, { 
        data: [6,3,2,2,7,26,82,172,312,433],
        label: "North America",
        borderColor: "#c45850",
        fill: false
      }
    ]
  },
  options: {
    title: {
      display: true,
      text: 'World population per region (in millions)'
    }
  }
});

So that, the solution is fetch all item from json and passing it like doing map for data like data.map((data) => data.mass) for datasets and the same for labels.

Update 1

let data = [{"date": "2020/07/28", "mass": 68.3}, {"date": "2020/07/29", "mass": 68.3}, {"date": "2020/07/30", "mass": 69.5}, {"date": "2020/07/31", "mass": 69.8}];

const labels = data.map((x) => x.date);
const ycoordinate = data.map((x) => x.mass);

var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: labels,
        datasets:[{
           data: ycoordinate

        }],
    },
    options: {}});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="chart" width="300" height="300"></canvas>

0👍

You try to acces an object field but you try to do it from an array this doesnt work that way. to achieve what you want you have to transform your array. You can do this with a map like this:

constlabels = data.map((x) => x.date)
const dataFormatted = data.map((x) => x.mass)

If you put those in your chart it will work

Leave a comment