Search code examples
javascripthtmljsonchartsgoogle-visualization

Creating 3D google chart from external json data to the html file


I have a json file which has following content -

{"Passed":"1","Failed":"1","Other":"2","Inconclusive":"3"}

I want to create a html file which will render a pie chart with legend as passed (green), failed (red), inconclusive (pink or blue) and other (orange). When mouse is hovered over pie chart it should show the numbers as given in the json.

Here's the html code for 3D pie chart i created -

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load("current", {packages:["corechart"]});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Execution State', 'Number of tests'],
          ['Inconclusive',     3],
          ['Failed',      1],
          ['Other',  2],
          ['Passed', 1],
        ]);

        var options = {
          title: 'Execution Result',
          is3D: true,
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="piechart_3d" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Now i need the external json file to be supplied to my html file as data instead of passing the inline data to the html. How can i achieve this? Any indicators to go about solving my issue will be much appreciated. Thank You!

EDIT: Here's the latest code which i'm using -

<html>
    <head>
        <title>Test Result</title>
        <link rel="icon" type="image/png" href="https://icons.iconarchive.com/icons/martz90/circle/256/plex-icon.png"/>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"/>
        <script src="https://www.google.com/jsapi"/>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"/>
        <script type="text/javascript">
    google.charts.load("current", {
  packages:["corechart"]
}).then(function () {
  $.ajax({
    url: "http://localhost/TestExecutionResult.json",
    dataType: "json"
  }).done(function (jsonData) {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Execution State');
    data.addColumn('number', 'Number of tests');

    $.each(jsonData, function (key, value) {
      data.addRow([key, parseInt(value)]);
    });

    var options = {
      title: 'Execution Result',
      is3D: true,
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
    chart.draw(data, options);
  });
});

        </script>
    </head>


    <body>
        <table>
            <tr>
                <th> Test result: </th>
            </tr>
            <tr>
                <td>
                    <div id="piechart_3d" style="width: 900px; height: 500px;"/>

                </td>
            </table>
        </body>

    </html>

and the json (TestExecutionResult.json) which i've published on localhost -

{"TestCasesPassed":0,"TestCasesFailed":1,"TestCasesOther":0,"TestCasesInconclusive":0}

EDIT 2:

<html>
    <head>
        <title>Production Smoke Test Result</title>
        <link rel="icon" type="image/png" href="https://icons.iconarchive.com/icons/martz90/circle/256/plex-icon.png"/>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"/>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
        <script type="text/javascript">
    google.charts.load("current", {
  packages:["corechart"]
}).then(function () {
  $.ajax({
    url: "http://localhost/TestExecutionResult.json",
    dataType: "json"
  }).done(function (jsonData) {
    
    // send data to console
    console.log(JSON.stringify(jsonData));

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Execution State');
    data.addColumn('number', 'Number of tests');

    $.each(jsonData, function (key, value) {
      data.addRow([key, parseInt(value)]);
    });

    window.alert(jsonData);
    var options = {
      title: 'Execution Result',
      is3D: true,
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
    chart.draw(data, options);
  }).fail(function (jqXHR, status, errorThrown) {
    // add fail callback
    console.log('error: ' + errorThrown);
  });
});
        </script>
    </head>


    <body>
        <table>
            <tr>
                <th> Test result: </th>
            </tr>
            <tr>
                <td>
                    <div id="piechart_3d" style="width: 900px; height: 500px;"/>

                </td>
            </table>
        </body>

    </html>

Solution

  • you can use jquery ajax to get the json data,
    build the google data table,
    and draw the chart.

    see following snippet...

    google.charts.load("current", {
      packages:["corechart"]
    }).then(function () {
      $.ajax({
        url: "path/data.json",
        dataType: "json"
      }).done(function (jsonData) {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Execution State');
        data.addColumn('number', 'Number of tests');
    
        $.each(jsonData, function (key, value) {
          data.addRow([key, parseInt(value)]);
        });
    
        var options = {
          title: 'Execution Result',
          is3D: true,
        };
    
        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
        chart.draw(data, options);
      });
    });
    

    just be sure to include jquery on your page...

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
    

    EDIT

    try sending the data to the console to make sure it is being received as expected.
    and, add the fail callback to see if the ajax call is receiving an error...

    see following snippet...

    google.charts.load("current", {
      packages:["corechart"]
    }).then(function () {
      $.ajax({
        url: "path/data.json",
        dataType: "json"
      }).done(function (jsonData) {
        
        // send data to console
        console.log(JSON.stringify(jsonData));
    
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Execution State');
        data.addColumn('number', 'Number of tests');
    
        $.each(jsonData, function (key, value) {
          data.addRow([key, parseInt(value)]);
        });
    
        var options = {
          title: 'Execution Result',
          is3D: true,
        };
    
        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
        chart.draw(data, options);
      }).fail(function (jqXHR, status, errorThrown) {
        // add fail callback
        console.log('error: ' + errorThrown);
      });
    });