【问题标题】:Google App Script; how to push data from nested JSON into array then to sheets谷歌应用脚​​本;如何将数据从嵌套的 JSON 推送到数组然后推送到工作表
【发布时间】:2021-08-18 03:05:09
【问题描述】:

8 月 18 日编辑;我在下面更新了我的脚本,以包含允许它在 JSON 响应中抓取嵌套数组的附加内容。

我不知道如何从嵌套的 JSON 数组中提取非空格式的数据。我的脚本执行并提取顶级数据,但是一旦我进入嵌套数组,它就会记录 null 并且在推送或追加中不显示任何内容。

我的总体目标是遍历工作表中的 URL 列表、发送 API 请求、接收响应并将信息记录在另一个工作表中。除了从 JSON 响应中的嵌套数组中获取数据之外,我能够成功完成所有操作。

这几天我一直在尝试解决这个问题,但我不擅长将 JSON 结果解析为数组,并且无法确定解决方案。任何提示将非常感谢!非常感谢。

其中一个 JSON 文件的示例;它们在格式上都是相同的。

{
  "kind": "youtube#channelListResponse",
  "etag": "MjhfUO2Z_x1Njr9Rw7uDjA1-bvM",
  "pageInfo": {
    "totalResults": 1,
    "resultsPerPage": 5
  },
  "items": [
    {
      "kind": "youtube#channel",
      "etag": "uHgaADZBzVjfmmqUFEHIy5RFmIk",
      "id": "UCuKkFu9WVxCRoj2EbWzIj3Q",
      "snippet": {
        "title": "AhnaldT101",
        "description": "Just a guy who loves to play anything Star Wars while having fun making other sorts of content that is sure to make you laugh and put a smile on your face!",
        "customUrl": "ahnaldt101",
        "publishedAt": "2012-12-09T04:34:18Z",
        "thumbnails": {
          "default": {
            "url": "https://yt3.ggpht.com/ytc/AKedOLTk3v99OfR76ONLecJpy80h4qaDQ2m9RGYRFPdgww=s88-c-k-c0x00ffffff-no-rj",
            "width": 88,
            "height": 88
          },
          "medium": {
            "url": "https://yt3.ggpht.com/ytc/AKedOLTk3v99OfR76ONLecJpy80h4qaDQ2m9RGYRFPdgww=s240-c-k-c0x00ffffff-no-rj",
            "width": 240,
            "height": 240
          },
          "high": {
            "url": "https://yt3.ggpht.com/ytc/AKedOLTk3v99OfR76ONLecJpy80h4qaDQ2m9RGYRFPdgww=s800-c-k-c0x00ffffff-no-rj",
            "width": 800,
            "height": 800
          }
        },
        "localized": {
          "title": "AhnaldT101",
          "description": "Just a guy who loves to play anything Star Wars while having fun making other sorts of content that is sure to make you laugh and put a smile on your face!"
        },
        "country": "US"
      },
      "contentDetails": {
        "relatedPlaylists": {
          "likes": "",
          "favorites": "",
          "uploads": "UUuKkFu9WVxCRoj2EbWzIj3Q"
        }
      },
      "brandingSettings": {
        "channel": {
          "title": "AhnaldT101",
          "description": "Just a guy who loves to play anything Star Wars while having fun making other sorts of content that is sure to make you laugh and put a smile on your face!",
          "showRelatedChannels": true,
          "showBrowseView": true,
          "unsubscribedTrailer": "9hXIxPXngCo",
          "country": "US"
        },
        "image": {
          "bannerExternalUrl": "https://lh3.googleusercontent.com/I9Ffei-ZhVZ116pR61k_kP40J2OqlUx6LmToadolqzZ9vaPs7j9a-y0Jdr2LMOyKUCjQgV-cJw"
        }
      }
    }
  ]
}

到目前为止我的脚本;

function listYTChannels() {
  var sheet = SpreadsheetApp.getActive().getSheetByName("YTChannel");
  const otherSheet = SpreadsheetApp.getActive().getSheetByName('YTChannelResults')
  var sheetLR = sheet.getLastRow();
  var data = sheet.getRange(1,2,sheetLR).getValues();


  data.forEach(function (row,index) {
    Logger.log(row, index);
    var response = UrlFetchApp.fetch(row);
    Logger.log(response.getContentText());
    var responseParse = JSON.parse(response.getContentText());
    Logger.log(responseParse);

    var responseData=[];  // this is an empty array to hold the data from responseParse
    var date = new Date(); // create new date for timestamp
    responseData.push(date); // this will use the timestamp created above
    responseData.push(responseParse.items[0].id);  // this works, follow this format
    responseData.push(responseParse.items[0].snippet.title);
    responseData.push(responseParse.items[0].snippet.description); 
    responseData.push(responseParse.items[0].snippet.customUrl);
    responseData.push(responseParse.items[0].snippet.publishedAt);
    responseData.push(responseParse.items[0].snippet.thumbnails.high.url);
    responseData.push(responseParse.items[0].snippet.thumbnails.high.width);
    responseData.push(responseParse.items[0].snippet.thumbnails.high.height);
    responseData.push(responseParse.items[0].contentDetails.relatedPlaylists.uploads);
    responseData.push(responseParse.items[0].brandingSettings.channel.title);

    Logger.log(responseData);
    otherSheet.appendRow(responseData);  // no issues here

  });

}

【问题讨论】:

  • 请提供您的预期输出
  • 这只是一张根据运行的查询数量添加了一定数量的行的表格——但我没有指定我想要的列。我将很快用最终脚本和输出结果更新我的原始帖子。我相信我在下面的 cmets 中找到了我正在寻找的解决方案。

标签: arrays json google-apps-script


【解决方案1】:

例如尝试,或从我的其他答案中挑选...

responseData.push(JSON.stringify(responseParse.items[0].snippet.description)); 

【讨论】:

  • 谢谢!这是我不明白的部分......非常有帮助。我将其与您在下面的其他答案一起使用,并在完成后用完整的解决方案更新我的原始评论。再次感谢!!对我很有教育意义。
【解决方案2】:

探索完整 json 的最简单方法是:

//Mike Steelson
let result = []; 
function getAllDataJSON(url) {
  if (url.match(/^http/)){var data = JSON.parse(UrlFetchApp.fetch(url).getContentText())}
  else{var data = JSON.parse(url)}
  getAllData(1,eval(data),'data')
  return result
}
function getAllData(niv,obj,id) {
  const regex = new RegExp('[^0-9]+');
  for (let p in obj) {
    var newid = (regex.test(p)) ? id + '.' + p : id + '[' + p + ']';
    if (obj[p]!=null){
      if (typeof obj[p] != 'object' && typeof obj[p] != 'function'){
        result.push([niv, (newid), p, obj[p]]);
      }
      if (typeof obj[p] == 'object') {
        if (obj[p].length){
          result.push([niv, (newid), p + '[0-' +(obj[p].length-1)+ ']', 'tableau']);
        }else{
          //result.push([niv, (newid), p, 'parent']);
        }
        niv+=1;
        getAllData(niv, obj[p], newid );
        niv-=1
      }
    }
  }
}  

结果是一个数组,您可以根据需要修改(通过过滤器、查询、脚本)。 https://docs.google.com/spreadsheets/d/1JuQHBAqI_Y1jI7N9XPA3yNGJEZDQ7Sf9FgVruji4Tpo/copy如果您需要从 json 中获取更多具体信息,请告诉我。

【讨论】:

  • 这非常有用,我将在另一个即将到来的项目中使用它,并将它的一部分用于这个项目。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多