Is there a way to transform standard JSON data into a format that can be interpreted by Google Visualization

Recently, I delved into the world of Google charts and was amazed by its capabilities. However, I encountered a hurdle when trying to integrate data from a SQL server view. To tackle this issue, I initiated a sample project to facilitate the process but have been struggling to get it functional. Below is my code snippet:

<script type="text/javascript">
        // Load the Visualization API and the piechart package.
        google.load('visualization', '1', { 'packages': ['corechart'] });

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

        function drawChart() {
            var jsonData = $.ajax({
                url: "api/Google",
                dataType: "json",
                async: false
            }).responseText;

            alert(jsonData);
            // Create our data table out of JSON data loaded from server.
            var data = new google.visualization.DataTable(jsonData);

            data.addColumn('string', 'Employee');
            data.addColumn('number', 'TotalNoOfReports');

            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
            chart.draw(data, { width: 400, height: 240 });
        }

    </script>

Although I am able to retrieve the correct JSON data string, I am facing issues when feeding this data into the DataTable() class as it does not display any data on the chart. I even attempted using data.AddRows(jsonData) but without success. It seems that Google requires a specific format for the data structure, like the one shown below:

{"cols":[{"id":"Col1","label":"","type":"date"}],
  "rows":[
    {"c":[{"v":"a"},{"v":"Date(2010,10,6)"}]},
    {"c":[{"v":"b"},{"v":"Date(2010,10,7)"}]}
  ]
} 

I am looking for a way to transform my jsonData into the aforementioned structured format or something more adaptable. The existing chart examples are limited to static data, whereas I need real-time database integration. Any assistance would be greatly appreciated.

Answer №1

My expertise in this particular area is limited, but perhaps one way to approach this problem is by converting the json data into a more readable format first and then using a loop to add rows. For example:

var jsonData = eval("(" + JSONObject + ")");

Then follow it up with:

for(var key in jsonData) {

    dataTable.addRows(row);

While my answer may be brief and constrained, there might be someone else who can offer a more comprehensive solution.

Answer №2

The format of the response has a slight variation, with additional components such as status code, request Id, and API version apart from just the dataTable section:

{version:'0.6',reqId:'0',status:'ok',sig:'5982206968295329967',table:{cols:[{id:'Col1',label:'',type:'number'},{id:'Col2',label:'',type:'number'},{id:'Col3',label:'',type:'number'}],rows:[{c:[{v:1.0,f:'1'},{v:2.0,f:'2'},{v:3.0,f:'3'}]},{c:[{v:2.0,f:'2'},{v:3.0,f:'3'},{v:4.0,f:'4'}]},{c:[{v:3.0,f:'3'},{v:4.0,f:'4'},{v:5.0,f:'5'}]},{c:[{v:1.0,f:'1'},{v:2.0,f:'2'},{v:3.0,f:'3'}]}]}};

For more detailed information, refer to:

https://developers.google.com/chart/interactive/docs/dev/implementing_data_source

Answer №3

Include the following code snippet to properly parse your JSON string:

var parsedObj = JSON.parse(jsonData); 

Next, pass the parsed object to a google DataTable instance like this:

var dataTable = new google.visualization.DataTable(parsedObj);

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

Developing an interactive selector within the on() event handler

My goal is to utilize the on() event for managing dynamically created code. It functions properly when the selector is hardcoded in the on() event. However, I aim to enable it to select different elements depending on which box they choose. $("body").on( ...

Why is $watch not working inside tabs in AngularJS?

Check out this example on Plunker Hello everyone, In the provided example, there are two input text boxes created - one outside the tab and another inside. A watch function has been implemented for both of them. However, the watch function for the input ...

Finding the parent element of an <image> that is linked by an <use> tag in SVG

Within my <svg> element, I have multiple <image> elements nested under a <defs> tag. These images are referenced by various <use> elements, creating a structure like the following: <svg xmlns="http://www.w3.org/2000/svg" ... ...

Efficiently processing a JSON object datalist in the AJAX success callback using JavaScript

I am having trouble parsing a JSON datalist in my AJAX success function. I have passed an object containing a list of data using JSON from the controller to the view, and now need help parsing the JSON object in the AJAX success function. Below is the code ...

Creating a GeoJSON leaflet map using a $.each iteration

I am struggling to create a GeoJson LineString using a $.each loop. Despite my efforts, I can't seem to make it work. Based on the information I've gathered, this should be functioning correctly. What mistake am I making? var geojson = { typ ...

Using React Native to take user input and store it in an array in

As a newcomer to react-native and javascript, I am unsure where to begin with this small project. Participants are allowed to pick one option for each question. Which type of pet do you prefer? a dog a cat What color would you like your pet to be? ...

What is the method for generating a random Vector3 inside a sphere?

Recently, I've been experimenting with creating a random point within a sphere. However, I seem to be struggling in getting it right. The current code I have written actually returns a point within a cube instead of a sphere. I suspect there might be ...

altering the value with the click of a button

I'm new to JavaScript and I've come across a function that adjusts the quantity of ingredients on a recipe. I want to update the value by simply clicking a button. I have jquery included, the classes are properly formatted, and they are linked w ...

Utilizing a List<> as a template - asp.net mvc

When I return a view with a List as a model, the code looks like this: List<Indications.Analysis.PrepaymentResult> resultsList = Indications.Analysis.PrepaymentResult.GetPrepaymentResult(indication.Model.Trx, indication.Model.ShockBpsDropList.Value, ...

Employing the search feature to pinpoint a related value

My goal is to fetch the value of .postingTitle for the specific job record that the user selects to apply for. I am using the code jobTitle = $('.applyButton').parents().find('.postingTitle').val(); to achieve this, but currently, I am ...

The alphanumeric identification is not connecting properly, resulting in a null output

Currently facing an issue with mapping the ID attribute from my JSON data. I've successfully mapped a similar attribute before, so I'm not sure what's causing the problem. Below is the model I have developed: import Foundation import Objec ...

A detailed guide on sending Joomla form information to a controller function using Ajax communication

Within my Joomla 3.3 form, I have integrated an ajax script aimed at dynamically updating some form fields. The core of the script looks like this: formdata = new FormData(); jQuery.ajax({ type: "POST", dataType: "json", timeout: 6000, url: "index.php?opt ...

Issue with Jquery/Js function not performing as expected

This Javascript function is really effective in adding and removing form elements. However, I have noticed that it does not remove the class "input-group col-md-12 row" when an element is removed. I would like to modify it so that it also removes that cla ...

"Creating an array in JavaScript and passing it to a C# MVC controller: a step-by-step guide

Is it possible to create an array in jQuery/JavaScript and then send it to my C# controller? I have a list of employees from a select multiple, which I can display like this: <div class="demo"> <select style="display:none" id="liste" ...

Unable to access object key data from JSON-SERVER

I am currently attempting to send a GET request to json-server in order to retrieve data from a nested object. However, the response I am receiving is empty instead of containing the desired data key. After thoroughly reviewing the documentation, I could ...

Using Javascript to store webpage content in an array

I have a unique API for a service I manage that returns values in a format similar to JSON, but not exactly the same. It works smoothly with most programming languages, but I'm encountering an issue when trying to access these returned values using on ...

Utilizing iOS Local Storage for Efficient Form Submission Handling

I feel like my brain is on the verge of exploding. I just can't seem to get this to work as intended, and I'm struggling to pinpoint the issue. Currently, I have a form that needs to be processed using AJAX. Before proceeding with that, I want ...

Increase the size of the SVG area

I'm still learning how to work with SVGs, so I appreciate your patience as I ask what may seem like a simple question. Currently, I have an SVG image that resembles a cake shape. See it here: https://i.sstatic.net/tDhUL.png Take a look at the code: ...

What is the process for extracting a json object as column values in postgresql?

Here is some data that needs to be converted: id | customer | region | circle ---------------------------------- 1 | verizon | ny | c3 2 | t-mobile | nj | c4 I want to transform the data into a JSON format using PostgreSQL JSON Out ...

Netlify Lambda function with Expressjs generates a fresh session for each incoming request

Good Evening, After successfully running my Expressjs API locally without utilizing lambda functions, I encountered an issue where every request created a new session once the lambda function was introduced. Below is the implementation of server.js and Das ...