[Chartjs]-Parsing values from external JSON file with Chart.js

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!

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 .

Leave a comment