Search code examples
javascriptgoogle-apps-scriptgoogle-apigoogle-shopping-api

Google Content Api for Shopping - List only wanted product features


I am utilizing the script below (https://developers.google.com/apps-script/advanced/shopping-content) I am wondering, instead of all the resources, how could I just list the product price for example?

/**
 * Lists the products for a given merchant.
 */
function productList() {
  var merchantId = 123456; // Replace this with your Merchant Center ID.
  var pageToken;
  var pageNum = 1;
  var maxResults = 10;
  do {
    var products = ShoppingContent.Products.list(merchantId, {
      pageToken: pageToken,
      maxResults: maxResults
    });
    Logger.log('Page ' + pageNum);
    if (products.resources) {
      for (var i = 0; i < products.resources.length; i++) {
        Logger.log('Item [' + i + '] ==> ' + products.resources[i]);
      }
    } else {
      Logger.log('No more products in account ' + merchantId);
    }
    pageToken = products.nextPageToken;
    pageNum++;
  } while (pageToken);
}


Solution

  • In your situation, how about the following modification?

    From:

    Logger.log('Item [' + i + '] ==> ' + products.resources[i]);
    

    To:

    Logger.log('Item [' + i + '] (product price) ==> ' + products.resources[i].price.value); // or products.resources[i].price.currency
    

    Note:

    • If you want to retrieve the data as an array, how about the following modification?

        function productList() {
          var merchantId = 123456; // Replace this with your Merchant Center ID.
          var pageToken;
          var pageNum = 1;
          var maxResults = 10;
          var res = []; // Added
          do {
            var products = ShoppingContent.Products.list(merchantId, {
              pageToken: pageToken,
              maxResults: maxResults
            });
            Logger.log('Page ' + pageNum);
            if (products.resources) {
              for (var i = 0; i < products.resources.length; i++) {
                res.push({id: products.resources[i].id, title: products.resources[i].title, price: products.resources[i].price.value}); // Added
                Logger.log('Item [' + i + '] (product price) ==> ' + products.resources[i].price.value); // or products.resources[i].price.currency
              }
            } else {
              Logger.log('No more products in account ' + merchantId);
            }
            pageToken = products.nextPageToken;
            pageNum++;
          } while (pageToken);
          Logger.log(res); // Added
        }
      

    Note:

    • In this answer, it supposes that you have already been able to use ShoppingContent.Products.list() method. Please be careful this.

    References: