简体   繁体   English

如何在 Apps 脚本 (javascript) 的 json 格式 API 调用中包含变量?

[英]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.我正在为 Google 表格开发一个自定义 function,它接收一个单元格值作为输入,并吐出来自 API 调用的响应。 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.知道在当前阶段 Google Analytics 报告 API 不能直接与自定义 function 一起使用,我正在关注这个这个解决方法。

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.运行 API 调用 Google Analytics 报告 API 的 function 包含一个带有指标、维度、过滤器等的 JSON 格式请求。问题是维度过滤器是可变的,我希望它是来自 Google 表格的输入。 However, I keep getting this error message:但是,我不断收到此错误消息:

GoogleJsonResponseException: API call to analyticsreporting.reports.batchGet failed with error: Field request.dimensionFilterClauses.filters.expressions is required. GoogleJsonResponseException:API 调用 analyticsreporting.reports.batchGet 失败,出现错误:需要字段 request.dimensionFilterClauses.filters.expressions。 (line 2, file "Code") (第 2 行,文件“代码”)

    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"}).如果我将变量 plate 更改为单个值,它就会起作用,即 function plateToCampaign(plate = {"fixed_value"})。 However this value will be different every time.但是这个值每次都会不同。 How do I fix this?我该如何解决?

After correcting your json as follows如下更正您的 json 后

  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)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM