Chartjs-How to separate a single json array into x and y values?

0👍

If i can assume that the attributes 0,1,2 are connected to a single Country. So that each graph = 1 country. Im also assuming you are using C# because the code seems to use Linq.

Dictionary<string, Graph> dict = new Dictionary<string, Graph>();
foreach (var country in CountryData.ToList().GroupBy(...))
{
  Graph g = new Graph();
  foreach(var countryNum in country.GroupBy(...)
  {
      g.addEntry(countryNum.key,countryNum...);
  } 
  dict.add("someName", g); // add different name for different graphs to avoid overriding values
}
return Json.SerializeObject(dict);

And the Graph class itself

class Graph {
   List<int> labels = new List<int>();
   List<int> values = new List<int>();

   public void addEntry(int label, int value){
       labels.Add(label);
       labels.Add(value);
   }
}

If my assumptions are correct then this should do the trick. If my assumptions are wrong, then i hope this can atleas help you move in the right direction.

Added bonus is, you can modify the Graph class to make it more generic for the graph.js. Like add in color info etc. So that on the JS part you just have a method makeGraph that takes this JSON as input and then based on values inside constructs a graph for you.

Leave a comment