Home > Mobile >  Process json data to generate bar graph
Process json data to generate bar graph

Time:05-05

I am trying to create a simple highchart bar graph with JSON that returns the value something like this :

[{
"name":"Apple",
"price":"40",
"date":"2022-02-04"
},
{
"name":"Mango",
"price":"80",
"date":"2022-08-02"
},
{
"name":"Orange",
"price":"60",
"date":"2021-01-09"
}]

and here is my fiddle http://jsfiddle.net/o246u8bt/ I am trying to achieve. It is not generating the bar with the different bar colors. Is this the right way of updating the series? Here is exactly the way I want my graph to look like http://jsfiddle.net/6hkcn4qf/2/

Thanks in advance!

CodePudding user response:

A couple of issues in your code. This is your function for ajax successful request:

success: function(data) {
  alert(JSON.stringify(data));
  const processedData = [];

  for (let key in data) {
    // alert(key);
  
    processedData.push({
      name: data[key].name,
      y: data[key].price
    });
  }

  options.series.data = processedData;

  Highcharts.chart('container', options);
}
1. Your data are strings, not numbers

Your JSON.stringified data are strings, so you're mapping strings in y: data[key].price.

Simply change into => y: data[key].price. With the plus sign you transform strings into numbers.

2. Your options.series is an array, not an object

So, you are not setting anything here: options.series.data = processedData (as options.series is an array of objects, it has indexes, not keys)

Simply change this into => options.series[0].data = processedData to create the data key of the first object inside the options.series array.

3. Use Stackoverflow's internal snippets, not external ones - if possible.

As external fiddles in a couple of months may be deleted or overwritten. Or the external site can be offline.

So, this question could become un-understandable or useless for others users in a short time.

  • Related