How to print json object property values? - javascript

I have a json object like this:
JsonQuery = ​'{
"from": 0,
"size": 200,
"sort": [{
"Modified": {
"order": "desc"
}
}],
"query": {
"bool": {
"must": [{
"term": {
"CollectionId": {
"value": "abcd"
}
}
}, {
"terms": {
"Container": ["en-us"]
}
}],
"must_not": [{
"wildcard": {
"_type": {
"value": "##"
}
}
}, {
"bool": {
"filter": {
"exists": {
"field": "DynamicProperties.MainSpec"
}
},
"filter": {
"exists": {
"field": "DynamicProperties.ExtendedSpec"
}
}
}
}]
}
}
}';
I am creating a javascript object by doing
var obj = JSON.parse(JsonQuery);
I go in chrome console and I write obj and hit enter and it displays the object properly but when I try to access the property of the object, it keeps saying undefined.
For example: I am using obj.size.

You only have a gremlin on your first line (JsonQuery = '), try to remove it and retry.
jsonQuery = '{"from":0,"size":200,"sort":[{"Modified":{"order":"desc"}}],"query":{"bool":{"must":[{"term":{"CollectionId":{"value":"abcd"}}},{"terms":{"Container":["en-us"]}}],"must_not":[{"wildcard":{"_type":{"value":"##"}}},{"bool":{"filter":{"exists":{"field":"DynamicProperties.MainSpec"}},"filter":{"exists":{"field":"DynamicProperties.ExtendedSpec"}}}}]}}}';
var obj = JSON.parse(jsonQuery);
console.log(obj.size);

Related

How to retrieve and process the data from the open dialog form?

I'm trying to process the response data in the open dialog but got stuck in this the retrieval.
I followed the step by step procedure given in this link: https://developers.google.com/chat/how-tos/dialogs but unfortunately, it didn't work as well.
Here is the sample code:
My goal is to get the data from the dialog form then process it. My pain point is in the code: event.common.formInputs.firstnumber.stringInputs.value[0] where it returns undefined reading value.
function openDialog(event) {
return {
"action_response": {
"type": "DIALOG",
"dialog_action": {
"dialog": {
"body": {
"sections": [
{
"header": "Addition Calculator:",
"widgets": [
{
"textInput": {
"label": "First Number",
"type": "SINGLE_LINE",
"name": "firstnumber"
}
},
{
"textInput": {
"label": "Second Number",
"type": "SINGLE_LINE",
"name": "secondnumber"
}
},
{
"textInput": {
"label": "Third Number",
"type": "SINGLE_LINE",
"name": "thirdnumber"
}
},
{
"buttonList": {
"buttons": [
{
"text": "Submit",
"onClick": {
"action": {
"function": "giveAnswer"
}
}
}
]
},
"horizontalAlignment": "END"
}
]
}
]
}
}
}
}
};
}
function giveAnswer(event) {
var firstterm = parseFloat(event.common.formInputs.firstnumber.stringInputs.value[0])
var secondterm = parseFloat(event.common.formInputs.secondnumber.stringInputs.value[0])
var thirdterm = parseFloat(event.common.formInputs.thirdnumber.stringInputs.value[0])
var sum = firstterm+secondterm+thirdterm
return {
"cardsV2": [{
"cardId": "addContact",
"card": {
"header": {
"title": "The SUM is:",
"subtitle": "Answer",
"imageUrl": "https://images.emojiterra.com/google/noto-emoji/v2.034/128px/1f4f1.png",
"imageType": "SQUARE"
},
"sections": [
{
"widgets": [
{
"textParagraph": {
"text": sum
}
}
]
}
]
}
}
]
}
}
I tried the example in here but didn't work as well. https://developers.google.com/chat/how-tos/dialogs#receive_form_data_from_dialogs

How can I include a variable in a json-format API call in Apps Script (javascript)?

I'm working on a custom function for Google Sheets, that receives a cell value as input and spits out the response from an API call. Knowing thatin the current stage Google Analytics Reporting API can't be directly used with the custom function, I'm following this and this workaround.
The function that runs the API call to the Google Analytics Reporting API includes a JSON-formatted request with metrics, dimensions, filters, etc. The problem is that the dimension filter is variable and I want that to be the input from Google Sheets. However, I keep getting this error message:
GoogleJsonResponseException: API call to analyticsreporting.reports.batchGet failed with error: Field request.dimensionFilterClauses.filters.expressions is required. (line 2, file "Code")
function plateToCampaign(plate) {
globalThis.r = AnalyticsReporting.Reports.batchGet({
"reportRequests":
[
{
"viewId": {"my_viewId"},
"pageSize": 1,
"dateRanges": [
{"endDate": "today", "startDate": "30daysAgo"}
],
"metrics": [
{"expression": "ga:pageValue"}
],
"dimensions": [{"name": "ga:sourceMedium"}, {"name": "ga:campaign"}, {"name": "ga:dateHourMinute"}],
"orderBys": {"fieldName": "ga:dateHourMinute","sortOrder": "DESCENDING"},
"dimensionFilterClauses": [
{
"filters": [
{
"dimensionName": "ga:pagePath",
"operator": "PARTIAL",
"expressions": [plate]
}
]
}
]
}
]
});
globalThis.c = r.reports[0].data.rowCount > 0? r.reports[0].data.rows[0].dimensions[0] : null
if (c === "google / cpc") {
globalThis.x = r.reports[0].data.rows[0].dimensions[1]
console.log(x)
return(x)
} else {
console.log(c);
return(c)
}
}
function doGet(e) {
const res = plateToCampaign(e.parameter.plate)
return ContentService.createTextOutput(JSON.stringify(res));
}
function test(plate) {
const url = {"my_web_app_url"}
return UrlFetchApp.fetch(url).getContentText();
}
If I change the variable plate to a single value then it works, ie function plateToCampaign(plate = {"fixed_value"}). However this value will be different every time. How do I fix this?
After correcting your json as follows
var reportRequests =
[
{
"viewId": "my_viewId",
"pageSize": 1,
"dateRanges": [
{"endDate": "today", "startDate": "30daysAgo"}
],
"metrics": [
{"expression": "ga:pageValue"}
],
"dimensions": [{"name": "ga:sourceMedium"}, {"name": "ga:campaign"}, {"name": "ga:dateHourMinute"}],
"orderBys": {"fieldName": "ga:dateHourMinute","sortOrder": "DESCENDING"},
"dimensionFilterClauses": [
{
"filters": [
{
"dimensionName": "ga:pagePath",
"operator": "PARTIAL",
"expressions": ["plate"]
}
]
}
]
}
]
you will be able to change plate for instance this way
function myfunction(item) {
var reportRequests =
[
{
"viewId": "my_viewId",
"pageSize": 1,
"dateRanges": [
{ "endDate": "today", "startDate": "30daysAgo" }
],
"metrics": [
{ "expression": "ga:pageValue" }
],
"dimensions": [{ "name": "ga:sourceMedium" }, { "name": "ga:campaign" }, { "name": "ga:dateHourMinute" }],
"orderBys": { "fieldName": "ga:dateHourMinute", "sortOrder": "DESCENDING" },
"dimensionFilterClauses": [
{
"filters": [
{
"dimensionName": "ga:pagePath",
"operator": "PARTIAL",
"expressions": [""]
}
]
}
]
}
]
reportRequests[0].dimensionFilterClauses[0].filters[0].expressions[0] = item
// include reportRequests in your own script ...
}
application
try this
function plateToCampaign(item = 'plate') {
var myRequest =
[
{
"viewId": "my_viewId",
"pageSize": 1,
"dateRanges": [
{ "endDate": "today", "startDate": "30daysAgo" }
],
"metrics": [
{ "expression": "ga:pageValue" }
],
"dimensions": [{ "name": "ga:sourceMedium" }, { "name": "ga:campaign" }, { "name": "ga:dateHourMinute" }],
"orderBys": { "fieldName": "ga:dateHourMinute", "sortOrder": "DESCENDING" },
"dimensionFilterClauses": [
{
"filters": [
{
"dimensionName": "ga:pagePath",
"operator": "PARTIAL",
"expressions": [""]
}
]
}
]
}
]
myRequest[0].dimensionFilterClauses[0].filters[0].expressions[0] = item
globalThis.r = AnalyticsReporting.Reports.batchGet({
"reportRequests": myRequest
});
globalThis.c = r.reports[0].data.rowCount > 0 ? r.reports[0].data.rows[0].dimensions[0] : null
if (c === "google / cpc") {
globalThis.x = r.reports[0].data.rows[0].dimensions[1]
console.log(x)
return (x)
} else {
console.log(c);
return (c)
}
}

How to check if array is empty or not and return value inside foreach in angular8

I have below data,
What i want to do is, i need to check values[] array in each object,
if it is empty then return true, else if values[] array has some record, it will return false.
i have created function for this, but it is reuturning false everytime.
if it is true thn i want to hide table. Table are multiple not single one, so if values arrayis empty thn only want to hide particular table.
{
"records": [
{
"context": {
"team": [
"MYTEAM-Consume-TEAM-SETUP-ADMIN"
]
},
"values": []
},
{
"context": {
"team": [
"TEAM1"
]
},
"values": [
{
"value": "red",
"label": "dd"
}
]
},
{
"context": {
"team": [
"Test"
]
},
"values": []
},
]
}
Code
hideContextTable(rows) {
const data = rows;
if (data.records) {
data.records.forEach(function (record) {
if (record.values.length === 0) {
return true;
}
});
}
return false;
}
deleteAllContextData(data) {
const tbl = this.hideContextTable(data);
console.log(tbl,"tbl");
if (tbl) {
this.showContextTables = false;
}
}
Simply check the length of returned data from filter function.
data = {
"records": [
{
"context": {
"team": [
"MYTEAM-Consume-TEAM-SETUP-ADMIN"
]
},
"values": []
},
{
"context": {
"team": [
"TEAM1"
]
},
"values": [
{
"value": "red",
"label": "dd"
}
]
},
{
"context": {
"team": [
"Test"
]
},
"values": []
},
]
};
function hideContextTable(data) {
const result = data.records.filter(record => record.values.length);
const flag = result.length ? true : false;
console.log(flag)
}
hideContextTable(data);
return in the higher order function of forEach will not cause flow to leave the hideContextTable function. You should use a variable that is accessible from outside that function and set it if the condition is met, then return that variable at the end of the function.
const rows = {
"records": [
{
"context": {
"team": [
"MYTEAM-Consume-TEAM-SETUP-ADMIN"
]
},
"values": []
},
{
"context": {
"team": [
"TEAM1"
]
},
"values": [
{
"value": "red",
"label": "dd"
}
]
},
{
"context": {
"team": [
"Test"
]
},
"values": []
},
]
}
function hideContextTable(rows) {
let isEmpty = false;
const data = rows;
if (data.records && data.records.values) {
data.records.forEach(function (record) {
if (record.values.length === 0) {
isEmpty = true;
return; // this is a higher order function
// meaning: it won't leave the context of hideContextTable
}
});
}
return isEmpty;
}
const test = hideContextTable(rows);
console.log(test);

Replace key and strings in array in JSON

I have this JSON below:
{
"class": "List",
"list": [{
"name": "HandsUp"
"schedule": {
"type": "probability",
"theme": "Regular",
"occurance": {
"next": 1607687249008.9834,
"prev": null
}
}
}, {
"name": "Listing",
"waitingScreenInfo": {
"__class": "WaitingScreenInfo",
"getRecapTime": 1607687753.7949834
},
"schedule": {
"type": "Waiting2",
"theme": "Listing",
"occurance": {
"next": 1607687249008.9834,
"prev": null
}
}
}
]
}
and I have this one:
{
"HandsUp": "HandsDown",
"Listing": "ImgList",
"Waiting2": "UpNDown"
}
The equivalent of the strings in the first JSON are in the second JSON and I wonder how can I make a function that finds the equivalents of the strings in the first JSON and then replace all of them even though if there is more than one?
You can do this
Go through the array
check if property name equals the key from your "repl" object
if yes reassign the value with the one in your "repl" object
let stru = {
"class": "List",
"list": [{
"name": "HandsUp",
"schedule": {
"type": "probability",
"theme": "Regular",
"occurance": {
"next": 1607687249008.9834,
"prev": null
}
}
}, {
"name": "Listing",
"waitingScreenInfo": {
"__class": "WaitingScreenInfo",
"getRecapTime": 1607687753.7949834
},
"schedule": {
"type": "Waiting2",
"theme": "Listing",
"occurance": {
"next": 1607687249008.9834,
"prev": null
}
}
}]
}
const repl = {
"HandsUp": "HandsDown",
"Listing": "ImgList",
"Waiting2": "UpNDown"
}
console.log("Before ", stru)
stru.list.forEach(element => {
// keys and values correspond at the index
let keys = Object.keys(repl);
let values = Object.values(repl);
for (let i = 0; i < keys.length; i++) {
if (keys[i] === element.name) {
element.name = values[i];
}
}
});
console.log("Afterwards ", stru)

Get buckets average of a date_histogram, elasticsearch

I have the following query where get the a data and I create an aggregation of each past hour:
query = {
"query": {
"bool": {
"must": [
{ "term": {"deviceId":device} },
{ "match": {"eventType":"Connected"} }
],
"must_not":[{
"query_string": {
"query": "Pong",
"fields": ["data.message"]
}
},
]
},
},
"size": 0,
"sort": [{ "timestamp": { "order": "desc" }}],
"aggs" : {
"time_buckets" : {
"date_histogram" : {
"field" : "timestamp",
"interval" : "hour",
},
}
}
}
I would like to get the average of a field from each hour interval (each bucket created by the aggregation). In this article they talk about something similar with what I wish to do:
http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/_looking_at_time.html
("What was the average latency of our website every hour in the last week?"). However, they don't explain exactly what to do in this case.
Does anyone know how to do that?
Just realized that I could do a nested aggregation and then calculate the average of a field inside a aggregation. Here is what I did and it's working properly now:
query = {
"query": {
"bool": {
"must": [
{ "term": {"deviceId":device} },
{ "match": {"eventType":"Connected"} }
],
"must_not":[{
"query_string": {
"query": "Pong",
"fields": ["data.message"]
}
},
]
},
},
"size": 0,
"sort": [{ "timestamp": { "order": "desc" }}],
"aggs" : {
"time_buckets" : {
"date_histogram" : {
"field" : "timestamp",
"interval" : "day"
},
"aggs" : {
"avg_battery" : {
"avg": { "field": "data.battery-level" }
}
}
}
}
}

Categories