Santhosh S. Santhosh S. - 1 year ago 75
jQuery Question

Json to Google chart dataTable JQuery

I have records in JSON format

"apr": 0.779,
"aug": 0.000,
"dec": 0.000,
"feb": 1.524,
"jan": -0.570,
"jul": 0.329,
"jun": 0.000,
"mar": 1.460,
"may": 0.000,
"nov": 0.000,
"oct": 0.000,
"ret": 3.557,
"sep": 0.000,
"vol": 2.649,
"year": 2017
}, {
"apr": 0.000,
"aug": 0.974,
"dec": -0.149,
"feb": 0.000,
"jan": 0.000,
"jul": 0.236,
"jun": 0.000,
"mar": 0.000,
"may": 0.000,
"nov": 0.000,
"oct": 0.898,
"ret": 1.488,
"sep": -0.471,
"vol": 1.428,
"year": 2016

Now I want to display in Google Line chart

Can any one help me to display in Google Line Chart?

Expecting Google Line chart like this

Answer Source

I have declared some variables for need. Here "returns" is the JSON data which is I am having (given above sample in Question)

   // var returns ===> JSON data
    var dataLength=null;
    var keyCount=null;
    var month=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];

Get the details from my json like below..

if( returns.length>0){ 
        dataLength=returns.length;/// Get Total number of Records ==> returns
        keyCount=Object.keys(returns[0]).length;/// Get Total number of key values having each object inside "returns"

Adding columns into DataTable ..

const data = new google.visualization.DataTable();    
 data.addColumn('string', 'Mois');
  for(var i=0;i<dataLength;i++){
        data.addColumn('number',returns[i]["year"]); /// Adding each year as Column into Datatable

And I am created temporary array to add data into DataTable "data"

for(var a=0;a<month.length;a++){ // Loop to iterate to get all MONTH values
        var arr = []; /// Declaring Empty array
        arr.push(month_Fr[a]);/// Push Month name (French) into Array 
        for(var b=0;b<dataLength;b++){ /// Loop to iterate to get all YEAR values
            monthValue=returns[b][month[a]]; /// Get value of each row object 
            arr.push(monthValue); /// Push object value into Array
        data.addRow(arr); // Adding Row into Datatable

creating chart elements

const chartOptions = {
      chart: {
        title: 'Performance'
      curveType: 'function',
      width: 900,
      height: 500
    const chart = new google.charts.Line($('#chart')[0]);
    chart.draw(data, chartOptions);

Finally my Line chart is :: click below link.

Line chart from JSON Data

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download