如何在Google App Script中解析JSON响应?

24

我正在使用Google AdWords/App Script,并从DoubleClick Search获得此响应。我试图将其解析到Sheet/数组中进行处理,但没有什么运气。谢谢你的关注。

这是原始代码:

var response = authUrlFetch.fetch(url, options);
 var data = JSON.stringify(response.getContentText());
 var parsedData = JSON.parse(data);

{
 "kind": "doubleclicksearch#report",
 "request": {
  "reportType": "advertiser",
  "columns": [
   {
    "columnName": "agency"
   },
   {
    "columnName": "agencyId"
   },
   {
    "columnName": "advertiser"
   },
   {
    "columnName": "advertiserId"
   }
  ],
  "includeRemovedEntities": false,
  "statisticsCurrency": "usd",
  "startRow": 0,
  "rowCount": 10000
 },
 "statisticsCurrencyCode": "USD",
 "rowCount": 2,
 "rows": [
  {
   "agency": "a",
   "agencyId": "11111111111111",
   "advertiser": "aa",
   "advertiserId": "11111111111111"
  },
  {
   "agency": "b",
   "agencyId": "222222222222222",
   "advertiser": "bb",
   "advertiserId": "22222222222"
  }
 ]
}

2
当我在谷歌上搜索“如何在Google App Script中解析JSON响应?”时,似乎得到了很多结果。难道没有一个有用的吗? - Pekka
1
我正在寻找解决办法,但是根据 JSON 的设置,我无法做到这一点。目前我还是卡住了,但我还在继续寻找。所以想问问别人。 - Josh
2个回答

60

这与常规的JavaScript类似。您可以使用 UrlFetchApp 服务获取JSON响应,然后使用点表示法访问属性。

try {
    const response = UrlfetchApp.fetch(url, options);
    const data = JSON.parse(response.getContentText());
    Logger.log(data.request.reportType);
} catch (f) {
    Logger.log(f.message);
}

4
嗨,阿密特,什么是点表示法?我尝试了你的代码,但它显示“TypeError: Cannot read property "reportType" from undefined”。我做错了什么?此外,我不得不使用UrlFetchApp而不是authUrlFetch。 - esaruoho
您检索的JSON没有属性类型reportType。@esaruoho - Anupam Rekha

2

使用API时的第一个答案的变化

var response = UrlFetchApp.fetch(externalposturl).getContentText();
var data = JSON.parse(response);
Logger.log(data.message);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接