Javascript json data read problem for double quote - javascript

I'm passing json data to javascript of Google Chart.
My json data format is
["Md. Aslam",170972.7,"gold"]
But in google chart javascript shows like
["JIANGSU LTD",170972.7,"gold"]
Here is showing " in respect of "
I need this data with " as I have given. How do I solve this?
My Controller (sending from data):
def data1 = table.executeQuery("select name, point from table") as JSON
render(view: "/report", model: [data1: data1])
My report.gsp (view of google chart):
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[ 'Element', "Density", { role: "style" } ],
${data1}
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("ord_variation"));
chart.draw(view, options);
}}
</script>
I'm using groovy/grails 3

Finally I got my solution as report.gsp
<g:applyCodec encodeAs="none">
${data1};
</g:applyCodec>

Change your code like below:
<script type="text/javascript">
var j = "${data}"; // data is your json data came from controller
var result = JSON.parse((j.split(""").join('"')).split("=").join(':')); //use result object
</script>
Hope this will helps you

Related

Annotate every Value in stacked column in google charts

I am trying to create an chart with google charts like:
stacked column chart with annotations in every value field.
Instead of the value it should show the name on every Value box in the stacked columns.
Name is always one row before the data in the google sheet - the data from google sheets can also be formated differently.
the posted code already does that, but only uses the same names for all rows instead of the custom names for every row/column.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1fUeGQpVGXpXmQ6QLLBgMf3VpaYuOnQIX24lBGgG7yoQ/gviz/tq?range=1:24");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
var data = response.getDataTable();
var chart = new google.visualization.ColumnChart(document.getElementById('columnchart'));
var options = {
width: 1920,
height: 1080,
legend: { position: 'none' },
column: { groupWidth: '95%' },
isStacked: true
};
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="columnchart" style="width: 100%; height: 100%;"></div>
</body>
</html>
(if the google sheet link won't work, here is the raw data)
Working code without google sheets (and minimal data, other label names):
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['API Category',
'Social', { role: 'annotation' },
'Music', { role: 'annotation' },
'File Sharing', { role: 'annotation' },
'Storage', { role: 'annotation' },
'Weather', { role: 'annotation' }
],
['2011', 98, 'Uschi', 53, 'Petra', 12, 'Max', 16, 'Mustermann', 6, 'Siegfried'],
['2012', 151, 'Susi', 34, 'Stackoverflow', 26, 'factor', 36, 'Ohnezahn', 49, 'Zahlos'],
['2013', 69, 'Rick', 27, 'Rolled', 22, 'Visual', 17, 'Studio', 15, 'Code'],
]);
var view = new google.visualization.DataView(data);
var options = {
width: 1920,
height: 1080,
legend: { position: 'none' },
column: { groupWidth: '95%' },
isStacked: true
};
var chart = new google.visualization.ColumnChart(document.getElementById("barchart_values"));
chart.draw(view, options);
}
</script>
</head>
<body>
<div id="barchart_values" style="width: 900px; height: 300px;"></div>
</body>
</html>
It s probably possible to accomplish that with Setcolumns() or setRows() but I just cannot wrap my head around it right now.
Maybe the question should be "Howto use ColumnDescription objects with data from external sources like google sheet"

C3 donut chart with data from JSON object

I'm attempting to create a C3 donut chart using data from a JSON object stored in a variable. The title renders correctly but the columns don't. If I hard code the column data (see commented out line) the chart renders but if I try to parse the column data from a JSON object it fails. However when I console log the column data ( in variable 'theatres'), it looks correct.
const txt = '{"theatres":"[[\'AMER INT\',386],[\'AMER US\',464],[\'APAC\',914],[\'EMEA\',706],[\'JP\',81]]","title":"94 Countries"}';
const dataobj = JSON.parse(txt);
var theatres = dataobj.theatres;
var title = dataobj.title;
console.log(dataobj);
console.log(theatres);
var chart = c3.generate({
bindto: '#chart',
data: {
type: 'donut',
// columns: [['AMER INT',386],['AMER US',464],['APAC',914],['EMEA',706],['JP',81]]
columns: theatres
},
size: {
height: 800
},
donut: {
title: title
}
});
What am I missing?
Thanks in advance!
The problem is that the value of theatres is still string:
"[['AMER INT', 386], ['AMER US', 464], ['APAC', 914], ['EMEA', 706], ['JP', 81]]"
So you need to use eval() to evaluate as valid array
const txt = '{"theatres":"[[\'AMER INT\',386],[\'AMER US\',464],[\'APAC\',914],[\'EMEA\',706],[\'JP\',81]]","title":"94 Countries"}';
const dataobj = JSON.parse(txt);
var theatres = dataobj.theatres;
var title = dataobj.title;
//console.log(dataobj);
//console.log(theatres);
var chart = c3.generate({
bindto: '#chart',
data: {
type: 'donut',
columns: eval(theatres)
},
size: {
height: 350
},
donut: {
title: title
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.10.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.20/c3.min.js"></script>
<div id="chart"></div>

how to save graphic in pdf without showing it in a div? -Google chart

I am making a graph with google chart, which displays me perfectly, what I want is to send it to save in pdf. I found a library that converts the image of the graph and later use the library that converts it into pdf, which it does, but it saves the image according to the size that was assigned, I show 4 graphics in 4 boxes and when I send it to save in pdf it comes out of the problem as it is being shown in the div, my question is can a second function without showing it on the page and sending it directly to save the pdf with the desired size?
when saved it comes out of size,
width: 400;
height: 200;
I want it to be saved with a size of
width: 800;
height: 400;
this is my codepen
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Density", { role: "style" } ],
["Copper", 8.94, "#b87333"],
["Silver", 10.49, "silver"],
["Gold", 19.30, "gold"],
["Platinum", 21.45, "color: #e5e4e2"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 400,
height: 200,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
var btnSave = document.getElementById('save-pdf');
google.visualization.events.addListener(chart, 'ready', function () {
btnSave.disabled = false;
});
btnSave.addEventListener('click', function () {
var doc = new jsPDF();
doc.addImage(chart.getImageURI(), 0, 0);
doc.save('chart.pdf');
}, false);
chart.draw(view, options);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="save-pdf" type="button" value="Save as PDF" disabled />
<div id="chart_div"></div>

google column chart change bar color not set dynamically

i want to set different column color . Only one color show in column . How i set dynamic color in google column color.
How can i set dynamic color of every column color .
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "/Dashboard/mTotalFileRefWise",
data: JSON.stringify({ PhaseID: $("#Projectlist").val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r);
var options = {
title: '',
legend: { position: 'none', maxLines: 9 },
colors: ['#00c0ef', '#DD4B39', '#DD4B39'],
width:500,
height:340,
animation: {
duration: 2000,
easing: 'out',
startup: true,
}
};
var chart = new google.visualization.ColumnChart($("#TotalFilesRefwise")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
$("#Projectlist").change(function () {
drawChart();
});
</script>
the colors configuration option applies each color in the array to each series in the data table
series are defined by y-axis columns in the data table,
which is each column after the x-axis, the first column
since you only have one y-axis column, only one color is applied
another method to apply colors is using a style column role in the data table
this allows you to define the color for each bar, right in the data table,
for example...
[
["Category","TotalAmount",{type:'string',role:'style'}], // <-- style role
["COST OF LAND",1572.2,'#00c0ef'], // <-- bar color
["DEVELOPMENT CHARGES",54.1,'#DD4B39']
]
if you don't want to change how the data is being built,
you can use a data view to assign the colors...
here, a data view is created, and a calculated column is added to determine the color.
the colors are pulled from the colors config option, based on row index of the data table...
(just be sure there are the same number of colors as there are rows in the data table)
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
role: 'style',
type: 'string',
calc: function (dt, row) {
return options.colors[row]
}
}]);
see following working snippet...
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var r = [["Category","TotalAmount"],["COST OF LAND",1572.2],["DEVELOPMENT CHARGES",54.1]];
var data = google.visualization.arrayToDataTable(r);
var options = {
title: '',
legend: { position: 'none', maxLines: 9 },
colors: ['#00c0ef', '#DD4B39', '#DD4B39'],
width:500,
height:340,
animation: {
duration: 2000,
easing: 'out',
startup: true,
}
};
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
role: 'style',
type: 'string',
calc: function (dt, row) {
return options.colors[row]
}
}]);
var chart = new google.visualization.ColumnChart($("#TotalFilesRefwise")[0]);
chart.draw(view, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="TotalFilesRefwise"></div>
note: need to use the correct version of google charts,
the jsapi library should no longer be used...
the new library...
<script src="https://www.gstatic.com/charts/loader.js"></script>
this will only change the load and setOnLoadCallback statements,
see snippet above...

Uncaught Error: Not an array

Im trying to populate a google chart with data that I'm fetching from an API at www.scb.se (The Swedish Statistics Bureau).
I'm using the following code:
$.ajax({
type: "POST",
url: 'http://api.scb.se/OV0104/v1/doris/sv/ssd/START/HA/HA0103/Livs',
data: '{"query":[{"code": "Varugrupp","selection":{"filter": "vs:VaruTjänstegrCoicopD","values":["01.1.7"]}},{"code": "ContentsCode","selection": {"filter": "item","values":["HA0103A1"]}},{"code": "Tid","selection":{"filter": "item","values": ["2004","2005","2006","2007","2008","2009","2010","2011","2012","2013","2014"]}}],"response": {"format": "json"}}',
success: function(data){
console.log(data);
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var jsonData = data;
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chartData = google.visualization.arrayToDataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(chartData, options);
}
}
});
When I "console.log(data)" I can see all the contents in the console but Charts keep telling me that data is not an array. What am I doing wrong?
Cheers!
The console log of "data":
Object {columns: Array[3], comments: Array[1], data: Array[11]}

Categories

Resources