Step-by-step guide on converting a JSON object into a dataTable suitable for Google Visualization Chart

I'm currently facing a challenge in creating a basic chart using data from a JSON Object.

Directly passing the JSON to a Line Chart is not possible, so I need to convert it into a DataTable. However, the process seems to vary depending on the structure of the JSON.

If my converted JSON string looks like this:

    var data = JSON.stringify(myJSONObject);
    var dataTableData = new google.visualization.DataTable(data); //throws error
    //var dataTableData = new google.visualization.DataTable(myJSONObject); //throws error
    //var dataTableData = myJSONObject //throws error
    var chart = new google.charts.Line(document.getElementById('line_top_x'));
    chart.draw(dataTableData, google.charts.Line.convertOptions(options));

No matter what approach I take, I always encounter the

"Error: First row is not an array"
message.

The structure of myJSONObject in JSON format:

(13) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {month: "February", column1: "1", column2: "2", column3: "3", column4: "4", …}
1: {month: "March", column1: "1", column2: "2", column3: "3", column4: "4", …}
2: {month: "April", column1: "1", column2: "2", column3: "3", column4: "4", …}
3: {month: "May", column1: "1", column2: "2", column3: "3", column4: "4", …}
4: {month: "June", column1: "1", column2: "2", column3: "3", column4: "4", …}
5: {month: "July", column1: "1", column2: "2", column3: "3", column4: "4", …}
6: {month: "August", column1: "1", column2: "2", column3: "3", column4: "4", …}
7: {month: "September", column1: "1", column2: "2", column3: "3", column4: "4", …}
8: {month: "October", column1: "1", column2: "2", column3: "3", column4: "4", …}
9: {month: "November", column1: "1", column2: "2", column3: "3", column4: "4", …}
10: {month: "December", column1: "1", column2: "2", column3: "3", column4: "4", …}
11: {month: "Total", column1: "1", column2: "2", column3: "3", column4: "4", …}
12: {month: undefined, column1: undefined, column2: undefined, column3: undefined, column4: undefined, …}
length: 13
__proto__: Array(0)

This is how myJSONObject looks when converted to a string (shown with console.log(data)):

[{"month":"February","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"March","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"April","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"May","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"June","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"July","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"August","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"September","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"October","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"November","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"December","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"Total","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{}]

Answer №1

it is necessary to transform each object into an array.

start by initializing an empty data table...

// initialize empty data table
var data = new google.visualization.DataTable();

then proceed to add the columns and rows...

// parse JSON
jsonData.forEach(function (jsonRow, indexRow) {
    // add columns
    if (indexRow === 0) {
        for (var column in jsonRow) {
            if (column === 'month') {
                data.addColumn('string', column);
            } else {
                data.addColumn('number', column);
            }
        }
    }

    // add row
    var dataRow = [];
    for (var column in jsonRow) {
        if (column === 'month') {
            dataRow.push(jsonRow[column]);
        } else {
            // convert string to number
            dataRow.push(parseFloat(jsonRow[column]));
        }
    }
    if (dataRow.length > 0) {
        data.addRow(dataRow);
    }
});

view the following snippet below for a working example...

google.charts.load('current', {
  packages: ['line']
}).then(function () {
  var jsonData = [{"month":"February","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"March","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"April","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"May","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"June","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},{"month":"July","column1":"1","column2":"2","column3":"3","column4":"4","column5":"5"},...

// create blank data table
var data = new google.visualization.DataTable();

// parse json
jsonData.forEach(function (jsonRow, indexRow) {
    // add columns
    if (indexRow === 0) {
        for (var column in jsonRow) {
            if (column === 'month') {
                data.addColumn('string', column);
            } else {
                data.addColumn('number', column);
            }
        }
    }

    // add row
    var dataRow = [];
    for (var column in jsonRow) {
        if (column === 'month') {
            dataRow.push(jsonRow[column]);
        } else {
            // convert string to number
            dataRow.push(parseFloat(jsonRow[column]));
        }
    }
    if (dataRow.length > 0) {...
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="line_top_x"></div>


note: If you prefer to generate the data table directly from JSON...

// create data table from json
var data = new google.visualization.DataTable(jsonData);

the JSON must be in a specific format, detailed here...
Format of the Constructor's JavaScript Literal data Parameter

{
  cols: [{id: 'A', label: 'NEW A', type: 'string'},
         {id: 'B', label: 'B-label', type: 'number'},
         {id: 'C', label: 'C-label', type: 'date'}
  ],
  rows: [{c:[{v: 'a'},
             {v: 1.0, f: 'One'},
             {v: new Date(2008, 1, 28, 0, 31, 26), f: '2/28/08 12:31 AM'}
        ]},
         {c:[{v: 'b'},
             {v: 2.0, f: 'Two'},
             {v: new Date(2008, 2, 30, 0, 31, 26), f: '3/30/08 12:31 AM'}
        ]},
         {c:[{v: 'c'},
             {v: 3.0, f: 'Three'},
             {v: new Date(2008, 3, 30, 0, 31, 26), f: '4/30/08 12:31 AM'}
        ]}
  ],
  p: {foo: 'hello', bar: 'world!'}
}

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

Struggling to choose an element with Selenium and Chrome?

I'm working on a script using Selenium and Chrome, but I'm facing issues with selecting and clicking on two specific elements. Let's take a look at the HTML code for these elements: HTML of Element 1: <td class="menuItem" id="tWlans" st ...

Attempting to call a nested div class in JavaScript, but experiencing issues with the updated code when implemented in

Seeking assistance. In the process of creating a nested div inside body > div > div . You can find more information in this Stack Overflow thread. Check out my JSFiddle demo here: https://jsfiddle.net/41w8gjec/6/. You can also view the nested div ...

How can the Vue-google-charts wrapper in Vue.js be used to generate a Google line chart?

What is the process for creating a line chart in Vue.js using the vue-google-charts wrapper? Can you provide guidance on adding rows and columns as data to the chart? Here is an example of how this can be done in Vanilla JS: var data = new google.visual ...

Utilize Javascript to extract data from arrays with multiple dimensions

If I have an array structured as follows: Let data = [ [bob, male, 90, pass][sam, male, 70, pass][grace, female, 75, pass][harry, male, 20, fail] ] and I am looking to extract all the names and store them in a separate array, how can this be achieved? Th ...

What is the best way to make an element's width match the width of the window?

When using the following code: $(my_div).width(window.innerWidth) The expected result is not achieved, as it does not take into account the vertical scrollbar. This causes the element to overflow the window, resulting in a horizontal scrollbar, which ca ...

JSON.parse encountered an unexpected character that is not whitespace following the JSON data

I'm having trouble fetching data from the database using the json object. Whenever I call the servlet, jQuery returns SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data. This error seems to occur only when the response contai ...

for each item, assign a unique ink color

Hello there! Currently, I am working on a straightforward online shopping MVC application. Within this application, there is a table containing three categories: Laptops, Mobiles, and Consoles. I have created a partial view that fetches these categories fr ...

Help needed with using Regex to restrict the number of alphabetical characters allowed

Struggling with configuring RegEx's. Seeking guidance to create a RegEx with the following criteria: Only allow numbers (0-9) Allow a period (.), negative sign (-), plus sign (+), dollar sign ($), and comma (,) Do not permit any alphabetic characte ...

The XMLHttpRequest() function throws NS_ERROR_FAILURE when sending requests to localhost using either an absolute or relative path

Encountering an error in Firefox 31 ESR: Error: NS_ERROR_FAILURE: Source file: http://localhost/Example/scripts/index.js Line: 18 Similar issue observed on Internet Explorer 11: SCRIPT5022: InvalidStateError The script used for AJAX function call i ...

JavaScript Tutorial: Storing HTML Text in the HTML5 Local Storage

I am looking to save the text that is appended using html() every time I click on a button. The goal is to store this text in HTML 5 local storage. $('#add_new_criteria').on('click',function(){ $('#cyc_append').html(&apo ...

The issue of integrating jQuery with the textarea CKEditor is still unresolved

I'm having an issue with applying the ckeditor function to append data in my code. I have included a cdn link for ckeditor in the header.php file, but it's not working as expected. How can I resolve this? <script> $(document).ready(func ...

Having trouble deciphering the request header value within the REST web API

Utilizing Ajax, I am storing the token in the request header and sending it to a Rest API. Here is the request sent to the web API: var xhr = new XMLHttpRequest(); $.ajax({ url: 'http://localhost:32253/api/UserDetail/Authenticate', head ...

Unwrapping React: Mastering the Art of Prop Extraction and Sharing

Imagine I have 2 input elements below, both with the same props except for the className <ReactCardFlip> <input type="text" maxLength={1} className={inputStyles.input} defaultValue={value} ...

Can you explain the functionality of Object.keys when used with a JavaScript variable?

In my application, there is a code snippet that looks like the following: var msg = data.data.modelState[Object.keys(data.data.modelState)[0]]; I'm curious about what the Object.keys portion of this code does and I would appreciate it if someone ...

Bringing in a feature within the Vue 3 setup

At the moment, I am attempting to utilize a throttle/debounce function within my Vue component. However, each time it is invoked, an error of Uncaught TypeError: functionTD is not a function is thrown. Below is the code snippet: useThrottleDebounce.ts imp ...

How can I extract the URL from the event listener in Cordova's in-app browser event and then automatically close it once a specific URL is reached?

In my journey with ionic version 1 (just starting out with ionic & angularjs), I encountered an issue while trying to close the in app browser upon reaching a specific URL. The problem arises from the fact that the event triggered on "loadstart" is o ...

Unable to access serialized select2 value in asp.net mvc controller

I'm facing a challenge with serializing and passing multiple controls inside a div to a controller via AJAX in my view. One of the fields, SchoolType, is a select2 multi-select dropdown. Model : public class SchoolModel { public string StudentN ...

What sets apart `Writes[MyClass]` from `Writes[MyClass.type]`?

My issue is that I've created a function which requires a Writes[Class.type] as input. However, when passing it the argument, the compiler recognizes it as Writes[Class] and fails to compile. Can someone explain the distinction between these two? ...

Organizing Angular Material Styles using Namespacing

In an attempt to develop reusable components with Angular 1.4.3 and Angular-Material 1.0.5, the goal is to seamlessly integrate these components across various applications. However, a challenge arises as the Angular Material CSS contains styling rules th ...

Loading a previously saved Sortable in Angular UI

I have a tabset that can be sorted, and it works as expected. However, I would like the user's tab order to be saved and not lost when they refresh the page. <uib-tabset ui-sortable="sortableOptions" class="tab-container" my-restrict access="st ...