Julian Martinez
Julian Martinez

Reputation: 113

Loading data into chart on html page

I am attempting to create a webpage that creates a simple chart using chart.js. I want to store all data related to the chart into a separate file ./file.json. When I attempt to load the html page while attempting to load data from ./file.json into chartdata, the chart fails to appear, but when I insert the data directly into script.js, it works.

Here is my faulty code within the script:

const chartdata = require('./file.json');
let myChart = document.getElementById('myChart').getContext('2d');

let massPopChart = new Chart(myChart, {
    type:'bar',
    data: {
        labels:[ 'Boston', 'Worcester', 'Springfield', 'Lowell', 'Dick' ],
        datasets:[{
            label: 'population',
            data: chartdata
        }]
    },
    options: {}
}); 

The chart successfully appears in the html page when I insert the data directly:

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

let massPopChart = new Chart(myChart, {
    type:'bar',
    data: {
        labels:[ 'Boston', 'Worcester', 'Springfield', 'Lowell', 'Dick' ],
        datasets:[{
            label: 'population',
            data: [135850, 52122, 148825, 16939, 9763]
        }]
    },
    options: {}
});

Any suggestions?

Upvotes: 0

Views: 560

Answers (1)

Jonah C Rowlinson
Jonah C Rowlinson

Reputation: 485

You need to pass the data to charts.js as an array instead of just as a JSON file. I've included an example below. It uses the fs library, which i think is included in node by default.

const fs = require("fs");
let myChart = document.getElementById('myChart').getContext('2d');

// read file sample.json file
fs.readFile('./file.json',
    // callback function that is called when reading file is done
    function(err, data) { 
        // json data
        var jsonData = data;
 
        // parse json
        var jsonParsed = JSON.parse(jsonData);
    }
);

let massPopChart = new Chart(myChart, {
    type:'bar',
    data: {
        labels:[ 'Boston', 'Worcester', 'Springfield', 'Lowell', 'Dick' ],
        datasets:[{
            label: 'population',
            data: jsonParsed
        }]
    },
    options: {}
}); 

Upvotes: 1

Related Questions