Categories: Java

How to Convert JSON String to Google Datatable for Google Charts

The article presents the solution to some of the issues that I faced while converting JSON string to Google Datatable. The primary reason for me to write an article on seemingly looking trivial issue is that I ended up spending lot of time in doing research and reaching to the solution.

 

Problem Scenario/Issues

One AJAX request is made to the server to retrieve the JSON data and draw the Google chart (LineChart in this example) using this JSON data.

Following is how the JSON data looks like after being sent from the server-side code:

{cols: [
     {id: 'task', label: 'Task', type: 'string'},
     {id: 'hours', label: 'Hours per Day', type: 'number'}],
rows: [
     {c:[{v: 'Work'}, {v: 11}]},
     {c:[{v: 'Work'}, {v: 11}]},
     {c:[{v: 'Eat'}, {v: 2}]},
     {c:[{v: 'Commute'}, {v: 2}]},
     {c:[{v: 'Watch TV'}, {v:2}]},
     {c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}
]}

Following is the AJAX & Javascript code which was written to achieve above mentioned scenario. However, the problem was that chart was not showing up.

$.ajax({
 url : $("#displayReportsForm").attr("action"),
 data : data,
 type : "GET",

 success : function(response) {  
  google.setOnLoadCallback(drawChart(response));  
 },
 error : function(xhr, status, error) {
  alert(xhr.responseText);
 }
});

function drawChart(jsonData) {    
 var containerId = "divId"; //Id of a div container within HTML to hold the chart
 try {
  var data = new google.visualization.DataTable(jsonData);
  var chart = new google.visualization.LineChart(document
    .getElementById(containerID));
  chart.draw(data, options);
 } catch (err) {
  alert( err.message );   
 }
}

On one of the related pages on stackoverflow, a problem was stated where the same jsonData was locally done like following, but the chart did not show up.

jsonData = "{cols: [{id: 'task', label: 'Task', type: 'string'},{id: 'hours', label: 'Hours per Day', type: 'number'}],rows: [{c:[{v: 'Work'}, {v: 11}]},{c:[{v: 'Work'}, {v: 11}]},{c:[{v: 'Eat'}, {v: 2}]},{c:[{v: 'Commute'}, {v: 2}]},{c:[{v: 'Watch TV'}, {v:2}]},{c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}]}"

 

Solutions

Following could be used to resolve the above-mentioned issues and get the chart show up.

1. If testing locally, DO NOT enclose jsonData within “” as shown above. If you would remove outer double quotes (“”) sign, it would work fine.

2. For the above method to work correctly, one would require to write following additional code within the method.

jsonData = JSON.stringify(eval("(" + jsonData + ")"));

Thus, the method would look like following:

function drawChart(jsonData) {    
 jsonData = JSON.stringify(eval("(" + jsonData + ")"));
 var containerId = "divId"; //Id of a div container within HTML to hold the chart
 try {
  var data = new google.visualization.DataTable(jsonData);
  var chart = new google.visualization.LineChart(document
    .getElementById(containerID));
  chart.draw(data, options);
 } catch (err) {
  alert( err.message );   
 }
}
Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

View Comments

  • Ajitesh - you have saved my sanity - thankyou! I've been trying to get this working for hours and your comments helped me resolve my problems

Recent Posts

Creating a RAG Application Using LangGraph: Example Code

Retrieval-Augmented Generation (RAG) is an innovative generative AI method that combines retrieval-based search with large…

19 hours ago

Building a RAG Application with LangChain: Example Code

The combination of Retrieval-Augmented Generation (RAG) and powerful language models enables the development of sophisticated…

1 day ago

Building an OpenAI Chatbot with LangChain

Have you ever wondered how to use OpenAI APIs to create custom chatbots? With advancements…

2 days ago

How Indexing Works in LLM-Based RAG Applications

When building a Retrieval-Augmented Generation (RAG) application powered by Large Language Models (LLMs), which combine…

7 days ago

Retrieval Augmented Generation (RAG) & LLM: Examples

Last updated: 25th Jan, 2025 Have you ever wondered how to seamlessly integrate the vast…

7 days ago

What are AI Agents? How do they work?

Artificial Intelligence (AI) agents have started becoming an integral part of our lives. Imagine asking…

4 weeks ago