I'm trying generate gantt chart from json string and I have weird problem with parsing Json string to Json object.
i have variable myString with json string looking like that:
{"c": [{"v": "496"}, {"v": "Task name 1"}, {"v": "9, "}, {"v": "Date(2018,6, 19)"}, {"v": "Date(2018, 6, 21)"}, {"v": null}, {"v": 100}, {"v": null}]}
after using var jsonData = JSON.parse(myString); values:"Date(2018,6, 19)"and"Date(2018, 6, 21)" are changed to: "Date(2018,7, 19)" and "Date(2018, 7, 21)"
And i don't know what's wrong with my code.
My full code:
$.ajax({
type: "GET",
url: URL,
data: data,
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response['chart_data']);
var jsonData = JSON.parse(response['chart_data']);
console.log(jsonData);
var chart_height=jsonData["rows"].length;
google.charts.load('current', {'packages': ['gantt']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(jsonData);
var options = {
width: document.getElementById("task_list").offsetWidth,
height:30*chart_height,
gantt: {
trackHeight: 30
}
};
var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
});
SOLUTION:
Thanks to user1531038 new Date() function was executed while parsing, and Date function counts months from 0 to 11.
It is working fine as expected as both Date(2018,6, 19) & Date(2018, 6, 21) are string :
Related
I've got a google line chart which shows the correct line; but the annotation of the Date is off by one month exactly. The json data has the correct date; but somehow google charts transforms it:
Anybody an idea why this happens?
no mistake, the correct month is being displayed
when using the following date constructor, the months are zero based...
Date(year, month, day, hour, min, sec, mill)
see following snippet...
console.log(new Date(2016, 0, 1)); // <-- Jan
console.log(new Date(2016, 1, 1)); // <-- Feb
console.log(new Date(2016, 11, 1)); // <-- Dec
following is another snippet to demonstrate using json with google charts...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable({
"cols": [
{"label": "Date", "type": "date"}
],
"rows": [
{"c": [{"v": "Date(2016,0,28,15,0,0)"}]},
{"c": [{"v": "Date(2016,1,28,15,0,0)"}]},
{"c": [{"v": "Date(2016,2,28,15,0,0)"}]},
{"c": [{"v": "Date(2016,3,28,15,0,0)"}]},
{"c": [{"v": "Date(2016,4,28,15,0,0)"}]},
{"c": [{"v": "Date(2016,5,28,15,0,0)"}]},
{"c": [{"v": "Date(2016,6,28,15,0,0)"}]},
{"c": [{"v": "Date(2016,7,28,15,0,0)"}]},
{"c": [{"v": "Date(2016,8,28,15,0,0)"}]},
{"c": [{"v": "Date(2016,9,28,15,0,0)"}]},
{"c": [{"v": "Date(2016,10,28,15,0,0)"}]},
{"c": [{"v": "Date(2016,11,28,15,0,0)"}]},
]
});
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(data);
},
packages:['table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
following is a php snippet to create the json date using the above constructor
<?php
$date1 = new DateTime();
$date2 = "Date(".date_format($date1, 'Y').", ".((int) date_format($date1, 'm') - 1).", ".date_format($date1, 'd').", ".date_format($date1, 'H').", ".date_format($date1, 'i').", ".date_format($date1, 's').")";
echo $date2;
?>
here is a php fiddle to test the above snippet...
I am unable to change the Pie Chart colors. Currently it is only the default colors.
How do I define the colors? Below is my current chartObject. It works just fine when I change to BarChart or ColumnChart ie bar colors change. Just not for the PieChart. What I am doing wrong?
chartObject = {"type":"PieChart",
"data":{"cols":[{"id":"label","label":"Action Status","type":"string"},
{"id":"label","label":"Number of Actions","type":"number"},
{"role":"style","type":"string","p":{"role":"style"}}],
"rows":[{"c":[{"v":"Open"},{"v":2},{"v":"ORANGE"}]},
{"c":[{"v":"Close"},{"v":1},{"v":"GREEN"}]}]},
"options":{"title":"Legal Register Tracking"}}
Add slices in options data object and give color json object 'slices': [{color:'yellow'},{color:'red'}] for each slices
var app = angular.module('myApp', ['googlechart']);
app.controller('MyController', function ($scope)
{
$scope.chartObject = {};
$scope.chartObject.type = "PieChart";
$scope.chartObject.data = {"cols":
[
{id: "t", label: "Topping", type: "string"},
{id: "s", label: "Slices", type: "number"}
],
"rows":
[
{c:
[
{v: "Mushrooms"},
{v: 3},
{color: 'black'}
]
},
{c:
[
{v: "Pepperoni"},
{v: 2},
]
}
]};
$scope.chartObject.options = {
'title': 'How Much Pizza I Ate Last Night',
'slices': [{color:'yellow'},{color:'red'}]
};
});
I'm making c3js chart that looks like:
var chart = c3.generate({
bindto: '#chart',
data: {
columns: []
}
});
Then I'm trying to use load function from it's api:
var data = [["Name", "15", "30", "45"], ["x", "1", "2", "3"]];
function update_graph(arg) {
var tmp = arg[0][1];
chart.load({
xs: {
tmp : arg[1][0] //binding data to x here and getting an error
},
columns: [
arg[0],
arg[1]
],
});
}
update_graph(data);
And I'm getting: Uncaught Error: x is not defined for id = "Name".
If I set in xs section: Name : arg[1][0] - it does work. But then I will not be able to draw different lines from different arrays with this function. What am I doing wrong ? Thank you.
Working code to make setting key/value to be generic from 'arg' 2D array:- jsFiddle
Solution is to construct the xs object first like:-
var xs = {};
xs[arg[0][0]] = arg[1][0];
xs[arg[2][0]] = arg[3][0];
and then use xs object in the chart.load function like:-
chart.load({
xs: xs,
columns: [
arg[0],
arg[1],
arg[2],
arg[3],
],
});
Note that key in xs object is not hardcoded to 'Name' or 'Age' string.
Hope this works for you.
Following example is working fine, with multiple lines defined in different arrays.- jsFiddle
var chart = c3.generate({
bindto: '#chart',
data: {
columns: []
}
});
var data = [["Name", "15", "30", "45"], ["x", "1", "2", "3"], ["Age", "45", "38", "25"], ["y", "1", "2", "4"]];
function update_graph(arg) {
var tmp = arg[0][1];
chart.load({
xs: {
Name : arg[1][0],
Age : arg[3][0] //binding data to x here and getting an error
},
columns: [
arg[0],
arg[1],
arg[2],
arg[3],
],
});
}
update_graph(data);
Not sure what the issue is, which version of c3js library are you using?
Please refer to the c3js example:- c3js Example
$scope.barchart = function(data,id,chtype,keydata)
{
var xs1 = {};
var key1 = $scope.obj.key;
var data1 = $scope.obj.data;
xs1[key1] = data1;
var id = c3.generate({
bindto : '#'+id,
data: {
xs:xs1,
columns: data,
type: 'scatter',
},
});
}
Hello i have problem to load data in flotchart.js
here's the original code that works
var pageviews = [
[1,2],
[2, 3]
];
var visitors = [
[1, 3],
[2, 2]
];
var plot = $.plot($("#site_statistics"), [{
data: pageviews,
label: "Unique Visits"
}, {
data: visitors,
label: "Page Views"
}]);
but when i change the data that i load from json it doesn't work.
here's the data json on load_statistik_bidang.php:
[{"data":[["1",12],["1",11],["3",10],["14",9]],"label":"EMSA"},{"data":[["1",12],["4",9]],"label":"BSSA"},{"data":[["1",2],["1",10]],"label":"OSSAC"}]
if i copy the json in manual it's works but when im using function to load the data it doesnt work .
code that i load the json is like this :
function loadMyData(){
$.ajax({
url:"load_statistik_bidang.php",
dataType: "json",
method:"get",
success: function(data){
tampung = data;
console.log(data.EMSA);
}
});
}
var plot = $.plot($("#site_statistics"), tampung);
any ideas for this? thanks
Your JSON is broken/invalid. You're not closing your first data array.
Should look like this:
[{
"label": "EMSA",
"data": [
[
"1",
12
],
[
"1",
11
]
] // <-- you forgot this
},
{
"label": "BSSA",
"data": [
[
"1",
12
],
[
"4",
9
]
]
}
]
You can use this site to validate it in the future:
http://jsonlint.com/
I am getting the following JSON object from a webserver in response object:
(JSON Array :[{"JUL":"5"},{"AUG":"7"},{"SEP":"9"},{"OCT":"11"},{"NOV":"13"}, {"DEC":"15"},{"JAN":"17"},{"FEB":"19"},{"MAR":"21"},{"APR":"23"},{"MAY":"25"},{"JUN":"27"}])
I am taking keys of the JSON object in an array
var al_key = [];
//For loop for x axis dispaly.
alert("al_key.length --------->"+al_key.length);
var jsonObj = []; //declare array
for (var i = 0; i < al_key.length; i++) {
jsonObj.push({value: i, text: al_key[i].value});
}
// Add axes
chart.addAxis("x", {min:1, max: 12 ,labels: jsonObj , fixLower: "major", microTicks: true, majorTickStep: 1});
chart.addAxis("y", { min: 0, max: 50, vertical: true, fixLower: "major", fixUpper: "major", includeZero: true });
However, it's not working the way I expect it to. Any suggestions as to where I am getting this wrong? Or alternative ways to display months on the x-axis dynamically? Thanks in advance for any help.
Pasted response as a question edit:
Actually i am getting JSONArray Object which contain single JSONObject which contains values like
//Server side coding..
JSONObject object=new JSONObject();
object.put("JAN":"17");
object.put("FEB":"19");
object.put("MAR":"21");
object.put("APR":"23");
object.put("MAY":"24");
object.put("JUN":"27");
JSONArray arrayObj=new JSONArray();
arrayObj.add(object);
On System.out.println(arrayObj); // our json appears like {"JAN":"17"},{"FEB":"19"},{"MAR":"21"},{"APR":"23"}, //{"MAY":"24"},{"JUN":"27"}];
On jsp:
//Call to the database to fetch the desired value
dojo.xhrGet( { url : "/POC/Action.do",
handleAs : "json",
sync: true,
load : function(response, ioArgs) {
alert("retrived response ------"+response);
for(var i in response)
for(var x in response[i])
output.push(response[i][x]);
alert("Get value to draw line chart---------------------->"+output);
},
error: function(response, ioArgs){
dojo.byId("grid").innerHTML = "An error occurred, with response: " + response;
return response;
},
handleAs: "json" });
the response object contain the return value (JSONArray object);
now this key is need to be displayed in the x axis of the chart. Do i need to again get the key and prepare the json object which is formed in the form said above by you..
In reply to your updated information:
Change the way you send the JSON (based on the limited info available,I am assuming is a Java servlet using the org.jon package)
JSONArray array = new JSONArray();
arrayObj.put (new JSONObject("{'month':'JAN', 'value':'17'}");
// and repeat for the rest of the data
You can use it then in your dojo chart as I wrote below (jsonObj3).
Original comment.
Check at the examples here, specially the part:
labels: [{value: 0, text: "zero"},
{value: 2, text: "two"},
{value: 4, text: "four"}
and add the two series
addSeries("Series A", [1, 2, 3, 4, 5], {stroke: {color: "red"}, fill: "lightpink"}).
addSeries("Series B", [5, 4, 3, 2, 1], {stroke: {color: "blue"}, fill: "lightblue"}).
For the series, the JSON might be
var months = ["JUL","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR","APR","MAY","JUN"];
var jsonObj2 = [];
for (var i = 0; i < months.length ; i++) {
jsonObj2.push({value: i, text: months[i]});
}
If you want one single JSON object, try arranging it like this:
var data = [{month: "JUL", value:"5"},
{month: "AUG", value:"7"},
{month: "SEP", value:"9"},
{month: "OCT", value:"11"},
{month: "NOV", value:"13"},
{month: "DEC", value:"15"},
{month: "JAN", value:"17"},
{month: "FEB", value:"19"},
{month: "MAR", value:"21"},
{month: "APR", value:"23"},
{month: "MAY", value:"25"},
{month: "JUN", value:"27"}];
var jsonObj3 = [];
for (var i = 0; i < data.length ; i++) {
jsonObj3.push({value: i, text: data[i].month});
}