How to return a Date value from JSON to Google Visualization API - json

is there a way to retrieve date value from JSON in Google Visualization API?
Here is the snipplet for playground please copy the code below into it
When you run the code you won't have anything in result. you should remove the quotes from the date value I marked with comment in order to retrieve result.
function drawVisualization() {
var JSONObject = {
cols:
[
{id: 'header1', label: 'Header1', type: 'string'},
{id: 'header2', label: 'Header2', type: 'date'}
],
rows:
[
{
c:
[
{v: 'Value1'},
{v: "new Date(2010, 3, 28)"} // <= This is the format I receive from WebService
]
},
{
c:
[
{v: 'Value2'},
{v: new Date(2010, 3, 28)} // <=This is the format Google API accepts
]
}
]
};
var data = new google.visualization.DataTable(JSONObject, 0.5);
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {'allowHtml': true});
}

I just ran into this problem myself, so I thought I'd paste the answer from the google api documentation, located here http://code.google.com/apis/chart/interactive/docs/dev/implementing_data_source.html#jsondatatable
"JSON does not support JavaScript Date values (for example, "new Date(2008,1,28,0,31,26)"; the API implementation does. However, the API does now support a custom valid JSON representation of dates as a string in the following format: Date(year, month, day[,hour, minute, second[, millisecond]]) where everything after day is optional, and months are zero-based."

I was running into same problem and above solution did not work. After searching for hours I found following post and the solution in there worked.
https://groups.google.com/forum/#!msg/google-visualization-api/SCDuNjuo7xo/ofAOTVbZg7YJ
Do not include "new" in the json string so it will be just:
v:"Date(2009, 9, 28)"

I suppose that the quote is not at the correct place in your snippet "new Date(2010, 3, 28")
Write instead "new Date(2010, 3, 28)"
Json format does not accept javascript object so the server return a string.
JSON knows only numbers, boolean constants, string, null, vector and 'object' (much more a dictionnary).
I suppose that you have to perform an eval() of the returned string (do not forget to check inputs).
Another alternative is to use a Regex to extract the fields something like /new Date\((\d+),(\d+),(\d+)\)/ will work.

Related

Cell google sheet as Json Source

I have a variable into Google Script for access to data through an API:
var ticket_data = { "header_items": [{ "label": "Cliente", "type": "text", "item_id": "2cba1baf-207c-4529-ab72-7d35363983fc","responses": {"text": "PRUEBA: ANALISIS FALLA 2"},},],"template_id":"template_5f9b4f399fe342ce94fefada009ee467"}
JSticket_data=JSON.stringify(ticket_data)
I can run UrlFetchApp.fetch() to access the API without error.
But if I store the variable data into a Google Sheet cell, and read the value like this:
var ticket_data=sheet.getRange('B1').getValue()
JSticket_data=JSON.stringify(ticket_data)
I get this value:
"{ \"header_items\": [{ \"label\": \"Cliente\", \"type\": \"text\", \"item_id\": \"2cba1baf-207c-4529-ab72-7d35363983fc\",\"responses\": {\"text\": \"PRUEBA: ANALISIS FALLA 2\"},},],\"template_id\":\"template_5f9b4f399fe342ce94fefada009ee467\"}"
UrlFetchApp.fetch() does not work correctly with that value.
I think that the problem is when I take the cell data by ticket_data=sheet.getRange('B1').getValue(), it take it as string, and then the JSON.stringify add a double quotes an then add the backslashes. I tried remove the backslash with replaceAll('\\','') but it did not work.
06-10-22
This is an Update after the answer 1 to add more information to my question.
Firs to all Thank you for your answer !! I'm sorry if I shoudn't write this update here. Please tell me where I must to do in the future
I'm sure I making something bad.
I have prepared the variable and parameters for UrlFetchApp as:
ticketJson = work_sheet.getRange('B1').getValue()
var params = {
method:"POST",
contentType:'application/json',
headers:{Authorization:"Bearer "+token},
payload: ticketJson,
muteHttpExceptions:true
};
var post_ticket = UrlFetchApp.fetch("https://api.website.io", params)
Logger.log(post_ticket)
the logger's answer is
Information {"statusCode":400,"error":"Bad Request","message":"Invalid request payload JSON format"}
but if I store the data into a variable and then excecute JSON.stringify() the results is OK.
var ticket_data = { "header_items": [{ "label": "Cliente", "type": "text", "item_id": "2cba1baf-207c-4529-ab72-7d35363983fc","responses": {"text": "PRUEBA: ANALISIS FALLA 2"},},],"template_id":"template_5f9b4f399fe342ce94fefada009ee467"}
JSticket_data=JSON.stringify(ticket_data) // if not excecute this, I get the same error that I tell before
I can't find where is the error Thanks again in advance
Omar
The first code snippet in the question gets a JavaScript object and converts it to a text string with JSON.stringify().
The second code snippet in the question gets a text string that does not need to be processed with JSON.stringify() in order to get a text string. It is a text string.
In other words, you can simply use this:
const ticketJson = sheet.getRange('B1').getValue();
...and use ticketJson as is in UrlFetchApp.fetch().

Trying to get some position of JSON using Observables

Sorry for the question, but I'm newer in Typescript and Ionic and Im a bit confused about how should I proceed.
I have a JSON file with 150 entries based on an interface I'm declared quite simple:
export interface ReverseWords {
id: number;
todo: string;
solution: string;}
On the other hand, I have a service which reads the json file and returns an Observable of this type (ReverseWords)
getReverseWords() {
return this.http.get<ReverseWords>('/assets/data/reves.json');}
On .ts file, I call the service and I have all the content of the JSON file. What I want to do (and Im not able to do) is get only one entry based on a random position.
On .ts file:
reverseWords: Observable<ReverseWords>; // All the JSON content
reverseWordsSelected: Observable<ReverseWords>; // I would like to get one entry here
On ngOnInit():
this.reverseWords = this.dataservice.getReverseWords();
Everything is fine until here, I've got all the content and I can log it in console. I'm using Observables so I need to subscribe to it to get the information. And I use rxjs/operators pipe and filter to try it, but nothing is showing in the chrome developer console (not even an error).
const reverseWordSelectedByPosition = this.reverseWords.pipe(filter(reverseWord => reverseWord.id === randomPosition));
reverseWordSelectedByPosition.subscribe(console.log);
Could anybody help me and tell me what I'm doing wrong?
Other thing I've tested is to do the following in the service:
getReverseWords() {
return this.http.get<ReverseWords[]>('/assets/data/reves.json');}
And then in the .ts file:
reverseWords: Observable<ReverseWords[]>;
But I have the same problem.
Finally, the most weird thing is that if I write in the .ts file this simple test:
const test = from([
{
id: 1,
todo: 'chapter',
solution: 'r-e-t-p-a-h-c'
},
{
id: 2,
todo: 'claustrofobia',
solution: 'a-i-b-o-f-o-r-t-s-u-a-l-c'
},
{
id: 3,
todo: 'keyboard',
solution: 'd-r-a-o-b-y-e-k'
}
]);
Everything is fine and I can see on the log only 1 entry if I choose 2, for example.
Any help or advice??
Thanks and sorry for the long approach!!
As TotallyNewb suggested, I show an example of the JSON file, with only 3 entries:
[
{
"id": 1,
"todo": "chapter",
"solution": "r-e-t-p-a-h-c"
},
{
"id": 2,
"todo": "claustrofobia",
"solution": "a-i-b-o-f-o-r-t-s-u-a-l-c"
},
{
"id": 3,
"todo": "keyboard",
"solution": "d-r-a-o-b-y-e-k"
}
]
Since you are getting the whole array you can use map
this.reverseWords.pipe(
map((items) => items[Math.floor(Math.random() * items.length)]), // Creates a random index based on the array length
)
.subscribe(console.info);
If you want to pass the result to reverseWordsSelected, you can change it to a Subject and pass the value to it from the subscription of reverseWords with .next().
You can check out this stackblitz for a working example

Populate array in react-redux-firebase

react-redux-firebase supports replacing ids with the corresponding value in a lookup object – like a join – through a config object called populates (and later using a convenient mapping function inside mapStateToProps).
Unfortunately, the documentation of react-redux-firebase is rather rudimentary in this area (and in others)...
Can someone tell me, whether it's possible to populate a list of ids?
For example:
// from:
{ friends: [1, 27, 42] }
// to:
{ friends: [
{ id: 1, name: 'Charlie' },
{ id: 27, name: 'Parker' },
{ id: 42, name: 'Brown' },
] }
Testing version 3.0.0, it seems that populating a list works exactly the same as replacing a single field. Instead of receiving back an object you will receive an array of replaced objects.

DotNet.Highcharts and proper JSON

I have an inconsistent issue with the JSON sent to highcharts. Highcharts does not always reject the JSON, but when it does, updating the JSON by hand to a proper format consistently fixes it:
Exmaple DotNet.Hightcharts output:
series: [{ data: [284, 49, 100, 19], name: 'some name' }, { data: [230, 250, 219, 878], name: 'some name 2' }]
when fixed to included quotes it works:
"series": [{ "data": [284, 49, 100, 19], "name": "some name" }, { "data": [230, 250, 219, 878], "name": "some name 2" }]
Is there a way to get DotNet.Hightcharts to output this format?
Looking at the DotNet.Highcharts source code, it seems it uses its own JsonSerializer which does not quote property names, and there's no option to change this behavior nor swap out the serializer for another one altogether. They have made it straight forward to change the formatting in code though, so it looks like changing the following lines in: DotNet.Highcharts/JsonSerializer.cs should do what you need:
const string JSON_PROPERTY_WITH_VALUE_FORMAT = "{0}: {1}";
const string JSON_STRING_FORMAT = "'{0}'";
to become:
const string JSON_PROPERTY_WITH_VALUE_FORMAT = "{\"0\"}: {1}";
const string JSON_STRING_FORMAT = "\"{0}\"";
So I'd say you options are:
Compile your own version of DotNet.Highcharts using the source code with the above alterations.
Convince the project developers to include such changes in the next release.
Use an alternative library such as Highcharts.Net which does quote names by default.
Use no library at all and just render your data into a literal placed inside the hand-coded Highcharts javascript, using a stand alone Json formatter like Newtonsoft.Json.
Before any of the above though, it does sound a bit odd that this problem only emerges as more data is added. It's not just a case of apostrophes in your data breaking the format is it? They don't appear to be being escaped in the formatter.

Ember Data 1.0 with none standard json

I'm looking to use json from Github's issues api with Ember Data.
The problem is that the return json is not formatted the way ember data wants it to be.
Github returns data as such.
[
{id: 0, title: 'test'},
{id: 1, title: "ect.."}
]
Where as Ember Data's RestAdapter expects it to be like:
{ issues: [
{id: 0, title: 'test'},
{id: 1, title: "ect.."}
] }
I assume based on some research that I need to override the Find and FindAll methods for the DS.RestAdapter
MyApp.Issue = DS.Model.extend({ ... });
MyApp.IssueAdapter = DS.RESTAdapter.extend({
host: 'https://api.github.com/repos/emberjs/ember.js',
find: function(store, type, id) {
...
},
findAll: function(store, type since) {
...
},
}
The problem is in the example if found there are a few out of data methods and it also does not explain how I can pass a array with out an key of "issues"
To be honest I'm really a complete noob to all this and most of this js is over my head but I feel like I'm close to figuring this out. Let me know if I'm on the right track.