nishanth gmk
nishanth gmk

Reputation: 57

Unable to convert the json to google charts required format in javascript

The json returned by controller below is of the below format:

[
{"classification":"CON","count":2},
{"classification":"PUB","count":1},
{"classification":"SENS","count":1}
] 

But the required format for google charts is

[
['classification','count'],
['CON',2],
['PUB',1],
['SENS',1]
] 

Below is the controller I am using:

[Produces("application/json")]
    [Route("api/Reports")]
    public class ReportsController : Controller
    {
        private readonly Documint.Models.DocumintDBContext _context;
        public ReportsController(Documint.Models.DocumintDBContext context)
        {
            _context = context;
        }
        [HttpGet("MDReport", Name = "rep")]
        public JsonResult Report()
        {
            var q3 = _context.Masterdocs
            .Where(m => m.CorpId == "AFRICUREIND")
                .GroupBy(s => new { classi = s.Classification })
                .Select(x => new { classification = x.Key.classi, count = x.Count() }).ToList();


            JsonResult result = Json(q3);


           return Json(q3);
        }
    }

Hence, I am doing some split operations, first converting it to an array which returns:

[classification,count,CON,2,PUB,1,SENS,1]

The array I am getting after the last for loop is

['[classification','count'],['CON',2],['PUB',1],['SENS','1]']

which should be actually as below:

[['classification','count'],['CON',2],['PUB',1],['SENS',1]]

Please note the undesired single quotes in the beginning and end of the above array. Below is my javascript and HTML code.

        // Load the Visualization API and the piechart package.
        google.charts.load('current', { 'packages': ['corechart'] });

        // Set a callback to run when the Google Visualization API is loaded.
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            var jsonData = $.ajax({
                type: 'GET',
                url: "/api/Reports/MDReport",
                dataType: 'JSON',
                async: false
            }).responseText;
            alert(jsonData);
            var split1 = jsonData.split("},");


            var split2, split3;
            var splitlist=[];
            var k,x,y;
            for (k = 0; k < split1.length; k++)
            {
                split2 = split1[k].split(",");


                for (x = 0; x < split2.length; x++)
                {
                    split3 = split2[x].split(":");

                    for (y = 0; y < split3.length; y++)
                    {
                        splitlist.push(split3[y]);


                    }

                }

            }

            for (var j = 0; j < splitlist.length; j++)
            {
                splitlist[j] = splitlist[j].replace('{', '');
                splitlist[j] = splitlist[j].replace('}', '');
                splitlist[j] = splitlist[j].replace('"', '');
                splitlist[j] = splitlist[j].replace('"', '');

            }


            var finallist = [];
            finallist.push(splitlist[0]);
            finallist.push(splitlist[2]);

            for (var n = 1; n < splitlist.length; n = n + 2)
            {
                finallist.push(splitlist[n]);

            }
            alert(finallist);
            for (var m = 0; m < finallist.length; m=m+2)
            {
                finallist[m] = "['"+finallist[m]+"'";
                if (isNaN(finallist[m + 1])) {

                    finallist[m + 1] = "'" + finallist[m + 1] + "']";
                }
                else
                {
                    finallist[m + 1] = finallist[m + 1]+"]";
                }

            }
            alert(finallist);


            var data = google.visualization.arrayToDataTable(finallist);

            var options = {
                title: 'Master Documents',
                is3D: true,
            };

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

        }

    </script>
    <div id="chart_div" style="height:500px;width:500px"></div>

Can someone please help me out with what is the correction that's needed. I am not able to figure out the mistake.

Upvotes: 0

Views: 42

Answers (1)

poke
poke

Reputation: 388463

Your best option is to do this in JavaScript. The process would be like this:

  1. Fetch the properly typed JSON from the server/controller. So you get back your first JSON.
  2. Parse the data and transform it into the required format for Google Charts.
  3. Pass the transformed data to Google Charts.

For step two, this could look like this:

// you would get this from your AJAX request
var data = [
    { "classification": "CON", "count": 2 },
    { "classification": "PUB", "count": 1 },
    { "classification": "SENS", "count": 1 }
];

var chartsData = [['classification', 'count']].concat(data.map(x => [x.classification, x.count]));

var chartsDataJson = JSON.stringify(chartsData);
console.log(chartsDataJson);
// [["classification","count"],["CON",2],["PUB",1],["SENS",1]]

Please do never ever try to parse JSON using string manipulation like you do there. JSON is a native format to JavaScript so you have JSON.parse and JSON.stringify for serializing and deserializing JavaScript objects from and into JSON.

Upvotes: 1

Related Questions