0

我正在使用將數據導入this page的Google電子表格應用程序腳本的Google應用程序腳本示例。 該示例正常工作,但我想更改它正在提取數據的網絡媒體資源。使用應用程序腳本更改Google Analytics API中的網絡媒體資源

我已經四處尋找示例並嘗試了各自的示例代碼迭代,但我沒有弄清楚它的正確性。有人可以用這段代碼來幫助我如何更改它來在我的個人資料中提取不同的屬性?

function runDemo() { 
    try { 

     var firstProfile = getFirstProfile(); 
     var results = getReportDataForProfile(firstProfile); 
     outputToSpreadsheet(results); 

    } catch (error) { 
     Browser.msgBox(error.message); 
    } 
} 

function getFirstProfile() { 
    var accounts = Analytics.Management.Accounts.list(); 
    if (accounts.getItems()) { 
     var firstAccountId = accounts.getItems()[0].getId(); 

     var webProperties = Analytics.Management.Webproperties.list(firstAccountId); 
     if (webProperties.getItems()) { 

      var firstWebPropertyId = webProperties.getItems()[0].getId(); 
      var profiles = Analytics.Management.Profiles.list(firstAccountId, firstWebPropertyId); 

      if (profiles.getItems()) { 
       var firstProfile = profiles.getItems()[0]; 
       return firstProfile; 

      } else { 
       throw new Error('No profiles found.'); 
      } 
     } else { 
      throw new Error('No webproperties found.'); 
     } 
    } else { 
     throw new Error('No accounts found.'); 
    } 
} 

回答

1

如果你指的是Analytics Service documentation,你會發現,所有的.getItems()方法返回「的名單...」什麼的,或陣列。請注意,該示例始終引用每個陣列的第一項,[0]。所以你只需要遍歷返回的數組來獲取所有的東西。

你所提到的這個函數的修改版本就是這樣建立起來然後返回一個數組allProfiles(相應的改動例子的其餘部分將需要作出完成這一數據的報告。)

function getAllProfiles() { 
    var accounts = Analytics.Management.Accounts.list(); 
    var allProfiles = []; 
    if (accounts.getItems()) { 
     for (var acct in accounts.getItems()) { 
     var accountId = accounts.getItems()[acct].getId(); 

     var webProperties = Analytics.Management.Webproperties.list(accountId); 
     if (webProperties.getItems()) { 
      for (var prop in webProperties.getItems()) { 
      var webPropertyId = webProperties.getItems()[prop].getId(); 
      var profiles = Analytics.Management.Profiles.list(accountId, webPropertyId); 

      if (profiles.getItems()) { 
       for (var item in profiles.getItems()) { 
       var profile = profiles.getItems()[item]; 
       Logger.log(profile); 
       allProfiles.push(profile); 
       } 
      } else { 
       Logger.log('No profiles found [webProperty="' 
        +webProperties.getItems()[prop].getName() 
        +'"]'); 
      } 
      } 
     } else { 
      Logger.log('No webproperties found [account="' 
       +accounts.getItems()[acct].getName() 
       +'"]'); 
     } 
     } 
    } else { 
     Logger.log('No accounts found.'); 
    } 
    return allProfiles; 
} 

或者,如果你知道你想要什麼,只是改變了索引值,這是在示例中全部爲[0],引用第一個帳戶的第一個Webproperties列表中的第一個項目。

+0

我現在意識到我有兩個帳戶具有多個屬性。不幸的是,我試圖明確索引值,它是從第一個(遺留)賬戶中提取的。我想從我的第二個帳戶提取數據。 - 我想從我的第二個帳戶提取數據。 – 2013-03-26 13:34:15

+0

您提供的代碼會在第21行上引發錯誤。未找到配置文件。 – 2013-03-26 13:36:58

+0

確實如此,但前提是沒有Web屬性的配置文件。 (順便說一下,不是我的代碼 - 這就是你的例子。)因爲它正在建立一個列表,所以記錄異常並繼續進行會更合適,所以我會做出這樣的改變。 – Mogsdad 2013-03-26 13:48:37

相關問題