Issue with Google Charts JSON data parsing

I'm working on creating a Google chart using my JSON object, but I keep encountering an error when executing

var data = new google.visualization.DataTable(Chartdata);

Below is my code, any assistance would be greatly appreciated.

 var Addresses = JSON.parse('{"With Address": 45532627,"Without Address": 10845793}');
        var Age = JSON.parse('{"18-25": 2162586,"26-35": 9995883,"36-45": 9486158,"46-55": 8729677,"56-65": 6913371,"65+": 10545270}');
        var Cellphone = JSON.parse('{"With Cellphone": 21536203,"Without Cellphone": 34842217}');

        google.charts.load("current", {packages:["corechart"]});
        google.charts.setOnLoadCallback(drawChart(Addresses,'Addresses'));
        google.charts.setOnLoadCallback(drawChart(Age,'Age'));
        google.charts.setOnLoadCallback(drawChart(Cellphone,'Cellphone'));

   function drawChart(Chartdata,name) {           
       var data = new google.visualization.DataTable(Chartdata);

       var options = {
         title: name,
         pieHole: 0.4,
         legend: 'left'
       };

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

Answer №1

initially, setOnLoadCallback should only be executed once, upon page load.
in addition, setOnLoadCallback requires a reference to a function, not the output of a function.

google.charts.setOnLoadCallback(drawChart);

vs.
google.charts.setOnLoadCallback(drawChart(Addresses,'Addresses'));

however, you can incorporate the callback within the load statement.

google.charts.load("current", {
  callback: function () {
    drawChart(Addresses,'Addresses');
    drawChart(Age,'Age');
    drawChart(Cellphone,'Cellphone');
  },
  packages:["corechart"]
});

subsequently, in order to generate a DataTable directly from JSON data, it must adhere to a specific structure
referenced here --> Format of the Constructor's JavaScript Literal data Parameter

alternatively, you can manually populate the table.

view the functional snippet below...

google.charts.load("current", {
  callback: function () {
    var Addresses = JSON.parse('{"With Address": 45532627,"Without Address": 10845793}');
    var Age = JSON.parse('{"18-25": 2162586,"26-35": 9995883,"36-45": 9486158,"46-55": 8729677,"56-65": 6913371,"65+": 10545270}');
    var Cellphone = JSON.parse('{"With Cellphone": 21536203,"Without Cellphone": 34842217}');

    drawChart(Addresses,'Addresses');
    drawChart(Age,'Age');
    drawChart(Cellphone,'Cellphone');
  },
  packages:["corechart"]
});

function drawChart(Chartdata,name) {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Category');
  data.addColumn('number', 'Value');

  for (var key in Chartdata) {
    if (Chartdata.hasOwnProperty(key)) {
      data.addRow([
        key,
        Chartdata[key]
      ]);
    }
  }

  var options = {
    title: name,
    pieHole: 0.4,
    legend: 'left'
  };

  var chart = new google.visualization.PieChart(document.getElementById(name));
  chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="Addresses"></div>
<div id="Age"></div>
<div id="Cellphone"></div>

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

Unable to modify images and nicknames that have been selected from the steamapi

Having trouble syncing images and nicknames? Try using this: https://www.npmjs.com/package/steamapi New to promises and stuck at a point in your code? Here is the snippet of your code: const SteamAPI = require('steamapi'); const steam = n ...

Creating a dynamic progress bar that scrolls for multiple elements

I am currently working on implementing a scrolling progress bar to show users how much of an article within a div they have read. For reference, something similar can be seen on this site. I have created my custom progress bar and coded it on fiddle, whe ...

Preserving the original "this" context while binding a callback for a React child

class Parent extends React.Component { constructor(props) { super(props) this.handleChildOnClick = this.handleChildOnClick.bind(this) } handleChildOnClick() { /* Here, I want to perform an action that involves both Child and Parent. ...

Effective methods for managing data transfer from MySQL to JSON to PHP?

Currently, I am utilizing DataTables, a jQuery plugin, to showcase data from a MySQL database. The information is manipulated into JSON format within the HTML using some PHP code. While this setup is functioning, it may not be the most efficient approach. ...

Angular 2's Conditional Validation: A Comprehensive Guide

Angular 2 offers straightforward validation, which is a great feature. However, the challenge lies in making a required field optional based on another field's selection. Below are the validation rules: this.contractsFilter = this.fb.group({ selec ...

Retrieving data from a Json file

I am working with a JSON object var data = "{"2144":{"quantity":"350"},"2095":{"quantity":"100"}}" Any suggestions on how to extract each value and display it in the specified order using jQuery? 2144 - quantity:350 2095 - quantity:100 ...

How to Implement Angular ngStyle with ChangeDetectionStrategy.OnPush?

Check out this StackBlitz demonstration that demonstrates how ngStyle is being used to style the h1 element in the following way: <h1 [ngStyle]="{'background-color': backgroundColor}" The component named HelloComponent employs the O ...

Guide to setting up Firebase pagination in a NextJS 13 server component

Currently, I am working on developing a product page that showcases all products and functions as a server component. The challenge I am facing is the inability to pass the last visible document snapshot required by the startAfter() query. Below is the fu ...

Menu Styled <ul> Not Activating handlerOut

My navigation menu is structured using an unordered list (<ul>) with customized styling (see markup & CSS below) <ul id="TopNavigation"> <li><a href="#" id="products" class="products">PRODUCTS</a></li> ...

How to iterate through a JavaScript array in reverse order using a for loop and the array's length property

When looking to iterate through an array with the values [8,7,6,5,4], some may wonder why a for loop using the length of 5 continues to function even though there is no element at index 5 in the array. for(let i=array.length;i>=0;i++){ //do somethin ...

Using Play Framework to override the apply method in a JSON Read combinator

I'm attempting to create something similar to the following: case class Data(name: String, dataList: List[Integer], isPossible: Boolean) { override def apply(name: String, list: List[Integer]): Data = { Data(name, list, list.exists((x: Inte ...

Issue encountered while making requests to ASP.NET web services using Javascript

Having some trouble making a call to an ASP.NET web service from Javascript here. No matter how I fully qualify the name, it just won't recognize the Web Method - trying to troubleshoot this. Snippet of my web.config file: <httpHandlers> ...

Breaking down a intricate JavaScript expression in order to reformat it into a different structure

As I explore the task of refactoring a legacy application, I find myself faced with complex JavaScript expressions stored in a database column. These expressions contain validation and conditional rendering logic that need to be translated into structured ...

Utilizing the Model URL Parameter in VueJS

In the context of , my objective is to dynamically modify a range input element and reflect that change in the URL. // Incorporating URL update with range input manipulation var Hello = Vue.component('Hello', { template: ` <div> &l ...

Mastering the art of completing a form using AJAX

I'm working on a checkbox that triggers AJAX to create a new log. It populates the necessary information and automatically clicks the "create" button. However, I'm facing an issue where the hour value is not changing. Any help on what I might be ...

The JavaScript-generated form element will not be included in the data submitted through the POST method

While it may appear that this question has been asked before, my specific inquiry seems to be unique as I have not found a similar answer in other threads. Therefore, I am initiating a new discussion. My issue revolves around a form which contains a link ...

Making changes to a JSON file's data

I have been working on updating the quantity and price in cart.json through the following code snippet: addProduct(id) { // Retrieve the previous cart data fs.readFile(p, (err, fileContent) => { let cart = []; if (!err) { car ...

Setting up a spotlight in three.js

After following the initial tutorial for three.js, I hit a roadblock when attempting to incorporate a point light into the scene. Despite numerous attempts to tweak my code, the cube remains unlit by the point light. var scene = new THREE.Scene(); var cam ...

What is the most effective method for parsing a JSON document?

There are several methods to read JSON files in Node.js, such as: Utilizing the FS Library Synchronous: var fs = require('fs'); var obj = JSON.parse(fs.readFileSync('file', 'utf8')); Asynchronous: var fs = require(' ...

Tips for avoiding external conversion of Enum to string when using the JsonStringEnumConverter annotation

I have encountered an issue while using the Microsoft Graph package, specifically with enums annotated with JsonStringEnumConverters. Let's take a look at an example enum: [JsonConverter(typeof(JsonStringEnumConverter))] public enum SomeEnum { Fir ...