使用 Google 脚本从嵌套 json 中的数组获取数据

Get data from array in nested json using Google Script

我需要修复我一直在处理的 Google 脚本。基本上,我有 json https://www.instagram.com/nike/?__a=1 returns 关于 Nike 在 Instagram 上的帐户的基本信息。我从 "biography" 等对象中检索数据没有问题。但是,当我尝试检索嵌套对象(数组)时,我做错了什么,因为结果是重复的(见附件)。谁能帮我弄清楚我做错了什么?

// the name of the sheet within your document
var sheetName = "Sheet1";
// the name of the Instagram account you want the follower count for
var instagramAccountName = "nike";

function insert() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(this.sheetName);
  var followers = [];
  var followers = captionArray(this.instagramAccountName);
  for(var i = 0 ; i < 3; i++) {
    sheet.appendRow([Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"), followers]);  
  };
}

function captionArray(username) {
  var i = 0;
  for(var i = 0; i < 3; i++) {
    var url = "https://www.instagram.com/" + username + "/?__a=1";
    var response = UrlFetchApp.fetch(url).getContentText();
    var caption = [];
    var caption = JSON.parse(response).graphql.user.edge_owner_to_timeline_media.edges[i].node.edge_media_to_caption.edges[i].node.text;
    return caption;
  };
}

我认为这是造成问题的原因:

  • 您对两个数组使用了相同的索引 (i),但第二个数组只有一个元素。
  • 您只需完成一个请求。

这段代码对我有用:

function captionArray(username) {
  var captions = [];
  var url = "https://www.instagram.com/nike/?__a=1";
  var response = UrlFetchApp.fetch(url).getContentText(); 

  var edges = JSON.parse(response).graphql.user.edge_owner_to_timeline_media.edges;

  for(var i = 0, limit = edges.length; i < limit; i++) {
    captions.push(edges[i].node.edge_media_to_caption.edges[0].node.text); 
  }

  return captions; 
}