DateTime format in Google Chart - javascript

I want to create a line chart by Google Chart API. I want to get data from AJAX method and set data to chart as javascript JSON array, but I have a problem with datetime format inside. Additional, a AJAX data is a string which generated from PHP. I parse returned string to JSON array which I want to set as chart data.
v1 = '{"Date(2023, 1, 1, 20, 00, 00)", ... }'; # returned string AJAX
v1 = jQuery.parseJSON(v1);
data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn({...something else...});
data.addRows(v1);
options = { ... };
chart = new google.visualization.LineChart(document.getElementById('linechart_material'));
chart.draw(data, options);
And I have this error message in console, when I try use Date(year, month, day, hour, minute, second) constructor (Google "Date String Representation" method) as first element of v1 array: Unhandled Promise Rejection: Error: Type mismatch. Value Date(2023, 1, 1, 20, 00, 00) does not match type datetime in column index 0
How to prepare datetime in JSON array and Google Chart API?

google's "Date String Representation" method only works when you are passing the json to the data table's constructor.
see following working snippet.
the json must be in a specific format, which you can see below,
or here: Format of the Constructor's JavaScript Literal data Parameter
however, they use a bad example on their page because they use the new keyword in front of the date value, which isn't required.
point being, you must have the json formatted as below, with keys for rows and columns...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var jsonData = {
"cols": [
{"label": "datetime", "type": "date"},
{"label": "value", "type": "number"}
],
"rows": [
{"c":[{"v": "Date(2023, 1, 1, 0, 0, 0)"}, {"v": 1}]}, // = Feb 1, 2023 (month number index is zero-based)
{"c":[{"v": "Date(2023, 1, 2, 0, 0, 0)"}, {"v": 2}]},
{"c":[{"v": "Date(2023, 1, 3, 0, 0, 0)"}, {"v": 3}]},
]
};
var dataTable = new google.visualization.DataTable(jsonData);
console.log('data table rows', dataTable.getNumberOfRows());
console.log('row 1 date', dataTable.getValue(0, 0));
});
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
from here: https://developers.google.com/chart/interactive/docs/datesandtimes#dates-and-times-using-the-date-string-representation
When serializing data using the JavaScript DataTable object literal notation to build your DataTable, the new Date() constructor cannot be used. Instead, Google Charts provides a Date string representation that allows your date or datetime to be serialized and parsed properly when creating a DataTable. This Date string format simply drops the new keyword and wraps the remaining expression in quotation marks:
"Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)"

Related

First char in an enviroment var is being stripped when using moment in Postman

Using moment in Prerequest:
var yesterday = moment().subtract(1, 'days').format("yyyy-MM-DD");
console.log(yesterday);
var pastDate = yesterday;
pm.environment.set("pastDate", yesterday)
Request Body:
"AccountId": 1,
"StartDate": {{pastDate}}
Response:
{
"errors": {
"StartDate": [
"Unexpected character encountered while parsing value: 2. Path 'StartDate', line 7, position 18.",
"Input string '022-06-26' is not a valid number. Path 'StartDate', line 7, position 27."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
}
However when looking at the value in the Enviroment:
pastDate: 2022-06-26
So it seems the first character of the variable is being stripped? Not sure how to address this.
The resolution I found was to put the var inside quotes, as JSON needs to recieve dates inside Quote in order to manipulate the value.

Google sheets API sorting by date

I'm using nodejs with google sheets API and I'm trying to sort data by column with date string that looks like this: 'dd.mm', for example '01.03'. Currently I'm trying to do it by using batchUpdate, but it doesnt work. It sorts by day, 01 is first, 02 is second etc... My request looks like this:
await googleSheets.spreadsheets.batchUpdate({
spreadsheetId,
requestBody: {
requests: [
{
sortRange: {
range: {
sheetId,
startRowIndex,
endRowIndex,
startColumnIndex,
endColumnIndex,
},
sortSpecs: [
{
dimensionIndex,
sortOrder,
},
],
},
},
],
},
});
How can I make google sheets API see the columns as dates, not as strings? Because I assume thats where the problem is, the date string is sorted like a normal string.
Format the range to date format of day.month in your Google Sheets.
Highlight column or range you want to format.
Click Format Tab -> Number -> Custom number format.
In the text box, insert this value: d"."m.
Click Apply.
Step by step example:
Google Sheets can now recognize the data as date, you can sort it now using the API.
Example:
Request:
{
"requests": [
{
"sortRange": {
"range": {
"sheetId": 0,
"startRowIndex": 0,
"startColumnIndex": 0,
"endRowIndex": 13,
"endColumnIndex": 1
},
"sortSpecs": [
{
"sortOrder": "ASCENDING",
"dimensionIndex": 0
}
]
}
}
]
}
Output:
Reference:
Custom date formatting

JSON data to valid data array in JS

I need to alter my JSON API from https://demo.piwik.org/?module=API&method=VisitsSummary.getVisits&idSite=7&period=day&date=last3&format=json&token_auth=anonymous
{"2017-12-21":767,"2017-12-22":571,"2017-12-23":31}
to a valid array for my charts in NVD3.js as
[ { "key" : "Page Visits" , "values" : [ [ 1025409600000 , 767] , [ 1028088000000 , 571] , [ 1030766400000 , 31] }]
NOTE: These dates do not match the JSON and Array but highlight the conversion needed, if anyone can explain to me the date format used in NVD3.js that would be great too.
If helpful, I can add the scripts used to get data and display the NVD3 Chart.
You can use array#map to convert your object to array. Then use [ { "key" : "Page Visits" , "values" : result }]; to get the required object.
var data = {"2017-12-21":767,"2017-12-22":571,"2017-12-23":31};
var result = Object.keys(data).map(k => [new Date(k).getTime(), data[k]]);
console.log(result);

Calling a RESTful web service using SSIS

I need to call a RESTful web service using SSIS.
The web service accepts a JSON object as a parameter - I can call this service by constructing the JSON object using JavaScript:
data = {
CustomerKey: "Demo",
ApiKey: " 9999AA99-999A-9A9A-99A9-99999999A999",
RegistrationNo: "REG N02",
InsuranceRef: "Ins Ref",
VehicleType: "Lorry",
CarMake: "Car Make",
CarModel: "Car Model",
ChassisNo: "ChassisNo",
GrossPlatedWeight: "GP weight",
ManufactureYear: 1999,
VehicleStatus: "Hired",
DeliveryDate: null,
TransferDate: new Date(2004, 4, 1, 0, 0, 0).toMSDate(),
LastMotDate: new Date(2013, 12, 1, 0, 0, 0).toMSDate(),
LastInspectionDate: new Date(2013, 1, 11, 0, 0, 0).toMSDate(),
LastServiceDate: new Date(2014, 2, 2, 0, 0, 0).toMSDate(),
InformationLog: "information log and more information",
VehicleNotes: "Vehicle Notes",
EntityReference: "reference",
UseRootOrgUnit: "true",
AddDictionaryItemIfMissing: "true"};
and posting the object to the web service. The web service also returns a JSON object.
However, javascript is not available to me in SSIS - is it possible to call such a web service using SSIS? If so, can anyone help me with a link to show the steps necessary? (I have no experience with SSIS).
Thanks.

Write JSON parser to format data for pie chart (HighCharts)

I was fighting with HighCharts quite some hours for formatting the data input to the series option.
Finally I saw the link here solved my problem for data formatting and input.
The data format that would be recognized by HighCharts pie chart is like this (format 1) as indicated by the link above:
[["chrome",15],["firefox",20]]
I actually want dynamic data input from external URL and format the data so that HighCharts can recognized it. The data format I got from the URL is like this (format 2):
[
{
"status": "Stopped \/ Idle",
"val": 17.469444444444,
}, {
"status": "Working",
"val": 0,
}, {
"status": "Headland Turning",
"val": 0,
}, {
"status": "Transport",
"val": 0.15333333333333,
}
]
which is already in JSON format.
I just want to know that is that necessary for me to write a parser for the data from format 2 to format 1? Or Am I missing something that HighCharts can recognize the JSON format data and I don't actually need to write a parser?
I am new to HighCharts so feel free to point that out if some of my problem description does not make sense..Thank you!
EDIT: Thanks for all guys answering my question!
When a script expects data in specific format, you often have to map your data to fit format. This can be modified in server code or using javascript
Can use jQuery $.map to reconfigure an object or array to another array.
DEMO: http://jsfiddle.net/qpsSe/1
Note that trailing commas in sample JSON need removing to validate JSON
/* "json" is your response object, modify variable names to match */
var chartData=$.map( json, function( obj,i){
return [[ obj.status, obj.val]];
})
$.map API Docs
Alternate method in native javascript
var chartData=[];
for( i=0; i<json.length; i++){
chartData.push( [ json[i]['status'], json[i]['val'] ])
}
AFAIK that's just how Highcharts wants its data. That being said, the parser is pretty easy:
var data; // this is your received data
var highchartsData = []; // this is data for highcharts
$.each(data, function(i, e) {
highchartsData.push([e.status, e.val]);
});
One thing to note is that if the data you're receiving is in text (say, a response from an AJAX call) then you need to convert it to a javascript object like so:
var data = $.parseJSON(textData);
You need to make a parser when assigning options as stated in HighCharts preprocessing
Basically, you parse the data and include it in the options:
var serie1 = json.map( function(e) {
return [e.status, e.val];
});
options.series.push({data: serie1});
Here is a working example using $.map and options in Fiddle
Since Highcharts 3.0, categories can also be extracted by giving each point a name and setting axis type to "category".
For a column bar chart this would be:
xAxis: {
type: 'category',
},
series: [{
data: [{
name: 'Point 1',
color: '#00FF00',
y: 1
}, {
name: 'Point 2',
color: '#FF00FF',
y: 5
}]
}]
You can bind chart with JSON data, directly.
You just need to set the json property names as highchart standard.
'Y' for value and 'name' for label.
Your JSON should be as like follow:
[
{
name: "Stopped \/ Idle",
y: 17.469444444444
}, {
name: "Working",
y: 0
}, {
name: "Headland Turning",
y: 0
}, {
name: "Transport",
y: 0.15333333333333
}
]

Categories

Resources