how to parse json data in appsscript - google-apps-script-api

I am trying to extract the number of goals from the retrieved json data shown in my appsscript log below:
Info {copyright=NHL and the NHL Shield are registered trademarks of the National Hockey League. NHL and NHL team marks are the property of the NHL and its teams. © NHL 2021. All Rights Reserved., stats=[{splits=[{season=20202021, stat={pim=4.0, faceOffPct=0.0, plusMinus=3.0, blocked=1.0, shifts=69.0, penaltyMinutes=4, shots=10.0, shortHandedTimeOnIcePerGame=01:59, shotPct=10.0, games=3.0, shortHandedTimeOnIce=05:59, shortHandedGoals=0.0, gameWinningGoals=0.0, overTimeGoals=0.0, powerPlayTimeOnIcePerGame=02:51, powerPlayTimeOnIce=08:34, timeOnIcePerGame=17:31, assists=2.0, timeOnIce=52:33, evenTimeOnIce=38:00, powerPlayPoints=0.0, shortHandedPoints=0.0, evenTimeOnIcePerGame=12:40, goals=1.0, powerPlayGoals=0.0, points=3.0, hits=3.0}}], type={gameType={id=R, description=Regular season, postseason=false}, displayName=statsSingleSeason}}]}
the appscript code i have used is:
function update() {
var response = UrlFetchApp.fetch("https://statsapi.web.nhl.com/api/v1/people/8473986/stats?stats=statsSingleSeason&season=20202021");
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
Logger.log(data.stats.goals);
}
how can I log the goals from the data shown in the apps script log image (above)?
thanks for the help!

finally got it.
Logger.log(result.stats[0].splits[0].stat.goals);

Related

(Google Documents) Way to create custom documents based on certain input variables?

Is there a way to have a paragraph of text get spit out when you have a certain input, from say a google questionnaire?
And make it so you could have say 5 inputs, and it would spit out 5 paragraphs of information, into one document?
For example:
If someone fills out a questionnaire where the first question is year of birth, the tool would spit out the first paragraph with a description of what the year they were born was like.
Second question would be their birth country, the tool would place a paragraph of text about their birth country into the document.
etc etc
Many thanks in advance for any help
It is possible to create documents using a specific criteria based in form responses. I created the following sample script using Google Apps Script so you can get the idea:
function docCreation() {
var ss = SpreadsheetApp.getActive().getSheetByName("Form Responses 1");
var range = ss.getDataRange();
var values = range.getValues().reverse(); //reverses the array to get the last value in the first position
var doc = DocumentApp.create("Testing doc"); // You can change the name to match a username or any other variable instead
switch (getMonth(values[0][1].toString())) {
case 'Aug':
doc.getBody().appendParagraph("This is a sample body for August");
break;
case 'Jul':
doc.getBody().appendParagraph("This is a sample body for July");
break;
}
}
// Second function that returns the month value of the date introduced by the user
// I separated it because it is not that relevant to the main goal
function getMonth(val){
var month = val.split(" ");
return month[1];
}
It is a very simple script that checks if the month of the date introduced by the user is August or July, and if so, it creates a doc with a simple text as paragraph.
The script is bounded to the Google Sheet of the form responses and you can create a trigger so that every time a user fills out the form, the script starts running to create the needed documents. Now as I mentioned, this is just a sample, and the logic and docs format would depend on your specific needs and usage.
References:
Class Body
Create document

Google Form Search and Pull Spreadsheet Data

Hi I have google spreadsheet that contains customers' ID and their shipping status. I want to create google form where customers are able to input each of their own ID, with the return that the google form shows their shipping status.
I tried to look for solutions in internet but there was no luck. I am not really good in programming, i hope there is answer to this problem without having me to do some hard programming.
The sample case can be seen in here: https://docs.google.com/spreadsheets/d/14vSAeZxEJTzbNLLYEiref6qt-CMqiVi8alheLcIBugM/edit?usp=sharing
Google form should show something a little bit like is shown in cell D1:E3.
Where customers can fill the form with their own customer id, and the google form shows the status.
Consideration
There is no way to respond back in a Google Form directly. You can't show custom validation messages after From submission either.
Proposed solution
What about using email addresses additionally to the customerID to retrieve the shipping status? In this way you can easily build a notification system that will send an email if a matching customer ID is found in your spreadsheet.
To build such system you will have to build a Form with a Trigger.
It is required a bit of programming but I will try to cover the most important parts the best I can:
Adapt your Database structure
Add the customers email addresses in the column C in order to be able to retrieve it using the same customer ID.
| A | B | C |
|----+--------+-------|
| ID | STATUS | EMAIL |
Build the Form Trigger
In the Form you are using click on the 3 dots from the top menu and select Script Editor. Here you will write the code that will power your notification system.
function installTrigger() {
// This function instructs the program to trigger the checkID function whenever a form response is submitted
ScriptApp.newTrigger('checkID')
.forForm(FormApp.getActiveForm())
.onFormSubmit()
.create();
}
function checkID(e) {
// This function will parse the response to use the customer ID to retrieve email address and shipping status from the Spreadsheet Database
var responses = e.response.getItemResponses(); // Gets the form responses
var id = responses[0].getResponse(); // Assuming the first answer (index 0) is the customer ID)
var found = SpreadsheetApp.openById('spreadsheet_id')
.getRange('Sheet1!A1:C8') // The spreadsheet cells range in A1 Notation
.getValues() // Retrieve their values in rows
.filter((row) => row[0] == id); // Filter the rows for the provided customer ID
if (found) {
var status = found[0][1]; //Column B
var email = found[0][2]; //Column C
var subject = "Shipping Status";
var message =
`Hello!
The status of the order number ${id} is: ${status}.`
MailApp.sendEmail(email, subject, message);
}
}
Install the trigger
From the Script Editor top menu run the installTrigger() function: Run>Run function>installTrigger.
You are done
Following these steps you have successfully set up the notification system. Now you can start sharing the Form link and accept responses.
References
Installable Triggers
Mail App

How to enable word level Confidence for MS Azure Speech to Text Service

How to get word-level confidence for each word using MS Azure speech to text service? Currently, I am getting confidence value for sentence-level and I need word-level confidence for further processing.
You can retrieve the wordLevelConfidence by adding the ‘format=detailed’ & ‘wordLevelConfidence=true’ to the URI
For example, the language set to US English using the West US endpoint is: https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=detailed&wordLevelConfidence=true.
If you use the SDK:
var config = SpeechConfig.FromSubscription(sub, "westeurope");
config.SetServiceProperty("wordLevelConfidence", "true", ServicePropertyChannel.UriQueryParameter);
//config.RequestWordLevelTimestamps(); in case you also want wordleveltimestamps
config.OutputFormat = OutputFormat.Detailed;
the word confidence values are not part of the result directly, Take a look at the below for complete result in JSON form.
recognizer.Recognized += (s, e) =>
{
var j = e.Result.Properties.GetProperty(PropertyId.SpeechServiceResponse_JsonResult);
By using this code: setServiceProperty("wordLevelConfidence","true", ServicePropertyChannel.UriQueryParameter);
This is how I did it
SpeechConfig config = SpeechConfig.fromSubscription(speechSubscriptionKey, serviceRegion);
config.setServiceProperty("wordLevelConfidence","true", ServicePropertyChannel.UriQueryParameter);
config.setServiceProperty("format", "detailed", ServicePropertyChannel.UriQueryParameter); //you have to do it in this order
And this to get the results back
PropertyCollection properties = result.getProperties();
String property = properties.getProperty(PropertyId.SpeechServiceResponse_JsonResult);

QueryScheduleRequest not working in Microsoft CRM 2011

I basically want to check if a particular user is free in a provided time range using QueryScheduleRequest. For this I am using the following piece of code to retrieve available timings of the user on today's date:
QueryScheduleRequest scheduleRequest = new QueryScheduleRequest
{
ResourceId = userResponse.UserId,
Start = DateTime.Today,
End = DateTime.Today,
TimeCodes = new TimeCode[] { TimeCode.Available}
};
QueryScheduleResponse scheduleResponse = (QueryScheduleResponse)serviceProxy.Execute(scheduleRequest);
However, I am not getting proper response in scheduleResponse as seen in CRM service calendar. The start and end dates are also getting changed in the response. For eg, say I enter Start and End date as 12th in scheduleRequest but in scheduleResponse they get changed to 12th and 13th respectively. I have checked that I am referring the correct user.
This is how the user's schedule looks like in CRM (Work Hours:10am to 7pm):
And this is how the result in scheduleResponse looks like:
Observe the dates and schedule getting changed. Is there any other way in which I can achieve this functionality?
Basically Dynamics CRM stores all dates in the database as UTC time.Crm Users has to convert into Users LocalTime.
After getting scheduleResponse. You can Use the below Code to get User Start time and End Time.
QueryScheduleResponse scheduleResponse = (QueryScheduleResponse)service.Execute(scheduleRequest);
foreach (var getTimings in scheduleResponse.TimeInfos)
{
DateTime startTime =Convert.ToDateTime(getTimings.Start.Value.ToLocalTime());
DateTime endTime = Convert.ToDateTime(getTimings.Start.Value.ToLocalTime());
}
Note:we have ExpandCalendarRequest Class also to Retrieve User Available Timings

How do you form a compound query using Bing Marketplace API?

I have an application that is using the new Bing API from the Azure Datamarketplace. I used to be able to query the Bing API using a simple syntax using OR AND, etc. That doesn't seem to work in the new API.
Old syntax:
"Jacksonville Jaguars" OR "NFL Jaguars" OR "Atlanta Falcons"
That would give me a query with any of those phrases (I am making a rt_Sports query for news).
I am calling HttpEncode on the query first, but am still not getting results. It works if I remove all the " marks, but then I am getting results sometimes for news about Falcons and Jaguars (the animals)... Not what I wanted.
Anyone have any idea how you can form a query that takes multiple phrases?
I have tried to not use the OR, not use the ', use a ", use the | instead of OR. All of these work against BING the website, just not in the API.
I just tried this via Bing and got 36 Million results:
NFL Football | Seattle Seahawks | New York Giants | Dallas Cowboys | New Orleans Saints | New England Patriots | Jacksonville Jaguars
Same thing in the API returns 0.
I got an email from a friend who I also emailed this question out to and his thought was that I was going about it wrong. That there should be a way to form a LINQ query off the Bing object with multiple where clauses.
But I don't see how that would be possible. You allow a BingSearchContainer and then call the News method on the container. The News method has only a single Query parameter.
var bingContainer = new Bing.BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search"));
bingContainer.Credentials = new NetworkCredential(App.BingAPIAccountKey, App.BingAPIAccountKey);
string unifiedQuery = "NFL Football | Jacksonville Jaguars | Atlanta Falcons";
var newsQuery = bingContainer.News(unifiedQuery, null, "en-US", "Strict", null, null, null, "rt_Sports", "Relevance");
newsQuery.BeginExecute(BingNewsResultLoadedCallback, newsQuery);
Try changing unifiedQuery to the following:
var unifiedQuery = "'NFL Football' or 'Jacksonville Jaguars' or 'Atlanta Falcons'";
I tried something very similar to your sample code, using this format for the query string, and it worked for me:
var bingUri = new Uri("https://api.datamarket.azure.com/Bing/Search/v1/", UriKind.Absolute);
var bingContainer = new BingSearchContainer(bingUri);
bingContainer.Credentials = new NetworkCredential(BingAPIUserName, BingAPIAccountKey);
var unifiedQuery = "'NFL Football' or 'Jacksonville Jaguars' or 'Atlanta Falcons'";
var newsQuery = bingContainer.News(unifiedQuery, null, "en-US", "Strict", null, null, null, "rt_Sports", "Relevance");
var results = newsQuery.Execute();
foreach (var item in results)
{
Console.WriteLine(item.Title);
}
Here are my results:
Fantasy Football 2012: Ranking the Top 25 RBs
NFL Football No Longer Just a Sunday Game
Ravens Notebook: Ed Reed decided to play in game vs. Falcons since he 'wasn't doing anything else'
PrimeSport Partners with Jacksonville Jaguars to Offer Tickets and Official Fan
Packages for all Home and Away Games in 2012 Season
Jaguars cut former Ravens wide receiver Lee Evans
Falcons left tackle Baker finally feels healthy
Jaguars release veteran WR Lee Evans
NFC West: 2012 NFL Training Camp
Atlanta Falcons 2012 NFL TV Schedule
Jaguars training camp: Veteran WR Lee Evans released
Jaguars score 18 points in second half to beat Giants 32-31
Jacksonville Jaguars put running back Maurice Jones-Drew on reserve/did not report list
Postcard from camp: Falcons
Questions abound as NFL preseason opens in earnest
NFL fantasy football: Ryan Mathews loses value
The format for the unifiedQuery string is basically the OData URI query string format. For a full description of how these query strings work, check out the OData URI conventions documentation at http://www.odata.org/documentation/uri-conventions.

Resources