Using JSON with Google Chart Tools

When referring to this example at , it is noted that the method data.addRows() requires a list of lists.

A URI (/data/mydata.json) can be accessed to retrieve the following data:

[["Canada", 66], ["Turkey", 10], ["Hungary", 23], ["Italy", 49]]

Despite attempting to use JQuery's $.parseJSON(), an error is encountered:

SyntaxError: JSON.parse: unexpected character

The question then arises of how to properly format and pass this data into the required method.

UPDATE

Further investigation showed that running just

alert($.parseJSON('/data/mydata.json'))
successfully parsed and displayed the data. The issue seems to lie with data.addRows() throwing the error.

Below is the complete code snippet:


google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart)
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Node Count');
data.addRows($.parseJSON('/data/mydata.json'));

var options = {'title':'Tor Nodes by Country',
           'width':800,
           'height':600};

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

}

Answer №1

JQuery excels at parsing JSON data, resulting in an array of arrays.

Check out this JavaScript example showcasing how it functions:

var json_data = "[[\"Canada\", 66], [\"Turkey\", 10], [\"Hungary\", 23], [\"Italy\", 49]]";
var parsed_data = $.parseJSON(json_data);

document.write('<table><tr><th>City</th><th>number</th></tr>');
for (var i=0; i < parsed_data.length; i++) {
    document.write('<tr><td>' + parsed_data[i][0] + '</td>');
    document.write('<td>' + parsed_data[i][1] + '</td></tr>');
}
document.write('</table>');

If you're uncertain about the way your data is being retrieved, be sure to specify that JQuery should parse it as JSON during retrieval.

Take a look at this JSFiddle link to view the contents of json_data

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

Can you please provide a detailed list of all the events that are compatible with the updateOn feature in Angular's ngModelOptions?

The reference documentation notes the following: updateOn: a string that specifies which event should be bound to the input. Multiple events can be set using a space delimited list. There is also a special 'default' event that aligns with the ...

How can we ensure that a child directive in AngularJS shares the same data as its parent?

My child directive needs access to the same data as its parent pages. What would be the most effective method for sharing this data? Should the child directive fetch the data separately, or should the parent send it through attributes? ...

Utilize the parsing functionality in three.js to extract JSON geometry data

After exporting a model from Blender using the three.js exporter and successfully loading it with the JSONLoader, my next challenge is to store the JSON information in a variable and parse it to display the model without having to load an external file. T ...

Having trouble with my Angular subscription - not behaving as I anticipated

I am facing an issue on my shop page where I have a FilterBarComponent as a child component. On initialization, I want it to emit all the categories so that all products are rendered by default. However, on my HomePageComponent, there is a button that allo ...

Error in MUI: Unable to access undefined properties (reading 'drawer')

Recently, I encountered an unexpected error in my project using MUI v5.0.2. Everything was working fine just a week ago with no errors, but now I'm facing this issue without any changes made to the code: Error: TypeError: Cannot read properties of un ...

JavaScript and PHP open-source libraries for enabling voice chat functionality

Seeking assistance on incorporating voice-chat functionality into my website through PHP and JavaScript. Are there any open-source libraries available for this purpose? I am willing to utilize Flash if necessary, but limited to using only Flash, JavaScri ...

Exploring Angular 4: Embracing the Power of Observables

I am currently working on a project that involves loading and selecting clients (not users, but more like customers). However, I have encountered an issue where I am unable to subscribe to the Observables being loaded in my component. Despite trying vario ...

Tips on incorporating Prisma model into prisma-offset-pagination

I am currently implementing pagination using the prisma-offset-pagination package. To do this, I need to utilize Prisma Model in my code, but I'm unsure of the correct approach: Refer to line: 02 const result = prismaOffsetPagination({ model: user ...

Using MongoDB's MapReduce feature along with the Date and % operator

I am encountering an issue with a Python script that I am using to aggregate large collections into smaller pieces and group them by timestamp. map = Code("function(number) {" "emit({" "ts : new Date(new Date((this.ts - (this.ts % (60 * number ...

JavaScript: Toggle between 2 functions using a single click event listener

I am facing an issue with coding a Sidebar that features an animated Burger Menu Button named "navicon1". The Menu Button utilizes the "open" class to create a cool animation effect. Moreover, I aim to have the functions "openNav" and "closeNav" toggled wh ...

Is there a way for me to retrieve dynamic text?

I used an "IF" statement to display dynamic text - if it's null, show something, otherwise show something else. However, I am getting a blank result. What did I do wrong? <View style={styles.rightContainer}> { () =>{ if(t ...

Crafting interactive image checkboxes

At present, the checkboxes in my application are quite basic with labels. However, our app designer has requested that we revamp this feature and make it more appealing by using clickable images that still function like checkboxes. Allow me to provide an ...

Having trouble locating the module in my Node.js application

I am encountering an issue with my application, the directory structure is as follows: myApp controllers cars.js models car.js app.js package.json In my code, I reference my model and controller in the following manner... var express = req ...

AngularJS, the element being referenced by the directive is empty

Currently, I am in the process of transferring a jQuery plugin to AngularJS simply for the enjoyment of it. Previously, when working with jQuery, my focus was on manipulating the DOM using jQuery functions within the plugin loading function. Now that I am ...

Safari AJAX glitch - Unable to load requested resource

Today, an unexpected bug has appeared in a web app I'm currently developing. Without making any changes to the code, this bug suddenly emerged: I am sending AJAX requests (using vanilla JavaScript instead of jQuery) to our local server running MAMP P ...

Display live data directly from a specific XML tag on a webpage

My project involves working with a local XML file that is being constantly updated by a third party. I am looking to create a web page that can dynamically read and display a specific XML tag without requiring the page to be refreshed. Additionally, I woul ...

Deleting a segment of content from a webpage

Currently, I'm in the final stages of completing a blackjack game. However, one aspect that I haven't implemented yet is the ability for the user to play again after finishing a round. My initial idea is to use a window.confirm dialog box, where ...

Steps for obtaining images using lazy loading: <img loading="lazy"

After successfully utilizing the JavaScript-executer to locate the ImageElement, I encountered an error when attempting to extract the URL for downloading the image.svg. The error message reads "NoSuchElementException." Below is a snippet of my code: ((J ...

What is the best method for targeting the clicked element using its class name?

I have a scenario where there are multiple elements with the same class name, but I am only interested in changing the class of the element that is clicked. var icon = $('.opener i'); // Need to target the class of the clicked element Functi ...

Overuse of jQuery's preventDefault() and stopPropagation() functions

A recent discussion with a coworker revealed some contrasting coding practices, mainly concerning his extensive use of the two aforementioned methods in event handlers. Every event handler he creates follows this same pattern... $('span.whatever&apos ...