How to use google chart using dynamic data from json

iam using mvc, i want to connect my data to google pie chart. so I used json to get a list of names and their score using the following code

public JsonResult list()
        {
     var result= list.GroupBy(i => i.Name).Select(i => new { word = i.Key, count = i.Count() 
return Json(result.ToList(), JsonRequestBehavior.AllowGet);
}

Using the google chart API

 google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {

        var jsonData = $.ajax({
            url: "list",
            dataType: "json",
            async: false
        }).responseText;
        var data = google.visualization.DataTable(jsonData);

        var options = {
            title: 'Certificate details',
            is3D: true,
        };    
        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
        chart.draw(data, options);
    }

I want to know how to get a list of key value pairs of my data in a pie chart. I searched Google for a long time, everyone gives an example of code with php. Thankyou.

+4
source share
2 answers

You can analyze this client part of the data as follows:

function drawChart () {
    $.ajax({
        url: "list",
        dataType: "json",
        success: function (jsonData) {
            var data = new google.visualization.DataTable();
            // assumes "word" is a string and "count" is a number
            data.addColumn('string', 'word');
            data.addColumn('number', 'count');

            for (var i = 0; i < jsonData.length; i++) {
                data.addRow([jsonData[i].word, jsonData[i].count]);
            }

            var options = {
                title: 'Certificate details',
                is3D: true
            };
            var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
            chart.draw(data, options);
        }
    });
}
+9
source
0

Source: https://habr.com/ru/post/1533671/


All Articles