Having difficulty transforming the JSON data into the necessary format for Google Charts using JavaScript

The JSON data returned by the following controller is structured as shown below:

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

However, Google Charts requires the data to be in the following format:

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

Below is the code snippet of the controller being used:

[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);
        }
    }

Due to the mismatch in data format, certain operations need to be performed:

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

After processing the array in the last loop, the data should look like this:

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

Kindly take note of the single quotes at the start and end of the array which are not desired.

Here is the relevant JavaScript and HTML code for reference.

        // 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>

If someone could provide guidance on the necessary corrections, it would be greatly appreciated as I am struggling to identify the error.

Answer №1

The most effective solution is to implement this functionality in JavaScript. The steps involved would be as follows:

  1. Retrieve the properly formatted JSON data from the server/controller to obtain the initial JSON.
  2. Parse the data and convert it into the necessary format for integration with Google Charts.
  3. Provide the converted data to Google Charts for visualization.

Regarding the second step, the process could resemble the following code snippet:

// data obtained from 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]]

It is highly recommended to avoid manually parsing JSON using string manipulation techniques. JSON is inherently supported in JavaScript, providing methods like JSON.parse and JSON.stringify for efficient serialization and deserialization of JavaScript objects to and from JSON format.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the property name of an object in Angular using $watch

Is there a way to monitor an object for changes in any of its properties, and retrieve the name of the property that changed (excluding newValue and oldValue)? Can this be accomplished? ...

NodeJS - The function app.listen is not defined in this context

I've come across a similar question before, but the answers provided didn't help me resolve my issue. The error message I'm getting is "TypeError: app.listen is not a function"; Here's my full code below. Thank you in advance for your ...

Developing a HTML button through Javascript that triggers a method with a single parameter when clicked

My current project involves creating HTML buttons through JavaScript using AJAX. Each time I click one of these buttons, it triggers an AJAX function. If the AJAX request is successful, it retrieves a number that will be utilized in a for loop. As the loop ...

Error thrown by loader.js at line 582 of internal/modules/cjs/loader.js

Encountered this error message in the console: Error : Cannot find module. The detailed error is provided below. Any suggestions on how to resolve this? internal/modules/cjs/loader.js:582 throw err; ^ Error: Cannot find module 'C:\Users ...

What would be the best approach to convert this jQuery code into a more structured object-oriented programming format

Recently, I began working on my first major front-end heavy website. My goal was to create a unique content management system-driven single-page website with over 100 internal pages. The URL would remain constant, but whenever a user clicked on any link b ...

Direct attention to the modal display

I'm having trouble auto-focusing an input field when a modal is displayed. Here's what I've tried, but it doesn't seem to be working: jQuery(document).ready(function($) { $('#myModal').on('show.bs.modal', functi ...

The online server is unable to access the route from the ajax function in a separate JavaScript file

I am currently working on a Laravel project where each view page has its own separate JS file. However, I have encountered an issue when trying to access route functions from AJAX post or get calls on the online server (Digital Ocean). The error message I ...

Tips for including or excluding a series of comma-delimited values from an input

HTML <div class="wrap_temi"> <ul class="list-inline list-unstyled"> <li class="list-inline-item"> <input type="checkbox" value="amici" autocomplete="off"> Amici </li> <li class="lis ...

I am facing an issue with body-parser not properly processing my request in express.js

Utilizing the Controller in my project. Snippet from app.js: var express = require('express'); var app = express(); const routes = require('./Routes/route'); const bodyParser = require('body-parser'); app.use('/', ...

Using Firebase with Arrays in Javascript

Currently, my team and I are working on a project using Firebase with Vue.js as the framework. We've come across a challenge regarding creating, updating, and deleting elements in a Firebase cloud document. For instance, within our 'people&apos ...

Struggling with integrating Skybox in THREE.js

My console is not showing any errors. I am utilizing the live server VS code extension to execute the JS code. Can someone please assist me?" HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"& ...

Utilizing the Android emulator to connect to the local database

I am currently working on implementing a tutorial from Android Hive that involves login and registration using PHP, MySQL, and SQLite. However, I have encountered some issues related to JSON parsing. Despite my efforts, I am unsure of how to proceed at thi ...

Is there a way to identify when no rows contain specific values in PostgreSQL or node.js and return false?

Here is an example of a table: P Q t f f t f f In SQL, is there a way to return false when querying for t t, but true when querying for t f, f t, or f f? Should this be handled with node.js by first doing a select and then using if-else statements based ...

The proper usage of middleware in vue-router

I've set up routes in Vue and added some middleware conditions before each route, but it's not functioning as expected. Below is the content of my router/index.js file: const token = computed(() => useAuthStore().token); // Main Router cons ...

Having trouble connecting to a webpage to fetch the JSON data

I am attempting to retrieve the JSON data from my webpage, but I am encountering an issue where the data is coming back as null. In order to troubleshoot this problem, I took a closer look at my code: HttpClient client = new DefaultHttpClient(); ...

Is it possible to incorporate a React app as a component within a static HTML page?

Looking to integrate the react-csv-viewer component into a static HTML page without deploying it on a local server. I've tried following the instructions from the React tutorial, but am struggling with the build process. My goal is simple - to use th ...

react validation for dropdown, react-datepicker, and hour input at intermittent intervals

I have integrated the following packages into my project :- react-datepicker library for selecting from time and to time date validation with date-fns, moment.js, additional validations using jQuery and lodash libraries/packages If you want to view my pr ...

Kendo Template Function: Angular JS version 1.6

I'm working with a currency column that looks like this: { field: 'INVOICE_AMOUNT_ORIGINAL', title: $translate.instant('invoiceAmount'), format: '{0:n}', template: '#= currency(dataItem.INVOICE_AMOUNT_ORIGIN ...

Implementing change event to activate select dropdown with jQuery

Is there a way to modify the code so that select2 and select3 are disabled by default, but become enabled only when an option is selected in the previous select dropdown (excluding the placeholder "Select your option")? In addition, I want the first place ...

The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them: List of Playlists: export default class Playlists extends Component { playlists = [ ... ]; render() { const {navigation} = th ...