1

I have created a simple pie chart using Chart.js. I want to link this to a JSON file on my computer, which is in the same local folder. I then want the data from the JSON file to show up on my pie chart, instead of it being taken directly from the script.

How do I go about doing this? This is my code.

  <script>
    var ctx = document.getElementById("myDoughnutChart");
    var myDoughnutChart = new Chart(ctx, {
        type: 'doughnut',
            data: {
                labels: ["Blue", "Red", "Green", "Orange", "Light Blue"],
            datasets: [{
                backgroundColor: ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF"],
                    data: [12, 19, 3, 5, 2],
                    }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                showAllTooltips: true,
                title: {
                    display: true,
                    text: "Responsive test"
                    },
                legend: {
                    display: false,
                    fullWidth: true,
                    labels: {
                    boxWidth: [50]
                    },
                }
            }
        });
    </script>

This is my JSON file, which is saved under "chart.json" - I am not sure if this is the correct format as I am a real newbie to this.

{"jsonarray": [{
    "Color": "Blue",
    "Value": 12}, 
    {
    "Color": "Red",
    "Value": 19}, 
    {
    "Color": "Green",
    "Value": 3}, 
    {
    "Color": "Orange",
    "Value": 5}, 
    {
    "Color": "Light Blue",
    "Value": 2}]
};

I understand a need to parse the JSON file but I have no idea how to do this - thank you so much in advance.

2 Answers 2

1

There are a couple parts here.

Step One: load the JSON from a file

I like using Fetch. If you use jQuery, you can also use $.ajax. Assuming the file is in the same directory as your JS code and is named chart.json:

  fetch('./chart.json')
    .then(function (response) {
      return response.json();
    }).then(function (json) {
      // drawChart fn to be created...see below
      drawChart(json);
    }).catch(function (error) {
      console.error(error);
    });

Note that if you are running this code locally, you will probably get an error about CORS if you try to visit the website directly from the filesystem (like file:///<path-to-file>/index.html).

Instead, you can run a local server easily. Go to the directory that contains your file in your terminal, and run:

python -m SimpleHTTPServer 8000

or

php -S localhost:8000

This serves up the current directory on port 8000. Then visit http://localhost:8000/

Also, make sure the JSON is valid (no semicolon at the end!).

Step Two: parse the JSON response

We're trying to make two arrays. One with numbers for data, and one with strings for Labels.

You can do this easily with map:

var graphData = json.jsonarray.map(e => e.Color);
// ["Blue", "Red", "Green", "Orange", "Light Blue"]
var graphLabels = json.jsonarray.map(e => e.Value);
// [12, 19, 3, 5, 2]

Step Three: bring it all together

window.addEventListener("DOMContentLoaded", draw);
function draw() {
  // Get the json file with fetch or $.ajax
  // Pass the json data to drawChart
}
function drawChart(jsonData) {
  /* get graphData and graphLabels
  draw chart with your existing code
  pass graphData and graphLabels in place of
  the hard-coded labels and data in your Chart initialization */
}

extending the idea:

Right now this code only supports a single dataset. The backgroundColor array is fixed, so if you do not have exactly 5 values, some of the background colors will be ChartJS's default gray.

You can further abstract the drawing code to support multiple datasets & even randomly generate colors to match the number of groups if you require it. Just swap out the hard-coded values as needed with variables you generate from your dataset. Hopefully this helps get you started!

Sign up to request clarification or add additional context in comments.

2 Comments

That's great thank you for taking your time to break this down. My only question now is where in the code I input variables graphData and graphLabels? I am a complete newbie to this and have minimal JS knowledge, thanks again
You can wrap your current code in a function that takes these variables, like function drawGraph(graphData, graphLabels) { // your existing code }. Then in your existing code, replace the hard-coded values with the variables passed in. So data: { labels: ["Blue", "Red", "Green", "Orange", "Light Blue"] becomes data: { labels: graphLabels and the same replacement for the data.
0

The json files are most of the time string type so the chart you want to generate I think it needs a kind of number type so you need to convert your JSON data to a number time check here,if you do the parsing of JSON correctly check here how its already answered , you'll be ok .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.