KUAN CHUNG LIN
KUAN CHUNG LIN

Reputation: 27

How to connecting web API from URL and used that data?

I complete the tutorial about count npm packages download times, now I can use my JSON web api from url, but I don't know how to parse it to rows with responseToRows() function, I can get data in Logger.log(). My JSON structure is

[
    {CODE:value,PRICE:value,QTY:value},
    {CODE:value,PRICE:value,QTY:value}...
]

The value I wish is:

function responseToRows(requestedFields, parsedResponse) {
  // Transform parsed data and filter for requested fields
  return response.map(function() {
    var row = [];
    requestedFields.asArray().forEach(function (field) {
      switch (field.getId()) {
        case 'CODE':
          return row.push(CODE);
        case 'PRICE':
          return row.push(PRICE);
        case 'QTY':
          return row.push(QTY);
        default:
          return row.push('');
      }
    });
    return { values: row };
  });
}

but I don't know how to row.push() in that

Upvotes: 0

Views: 115

Answers (1)

mshcruz
mshcruz

Reputation: 1987

There are a few additional changes that you need to make to the original function from the tutorial:

  • Probably you won't use the requestedFields parameter as it is used in the tutorial, since it's an object based on what is used by Data Studio. So you can remove it and just go over the keys of each object you're passing (see code below).
  • The parsedResponse argument is not used in the function and you're using response instead, so you need to change the argument's name as well.
  • The function inside map is missing an argument name that will be used when pushing values to the row inside the switch (see code below). I named it transaction, but you can use another name if you want.

Doing these modifications, the code becomes something like the following:

function responseToRows(response) {
  return response.map(function(transaction) {
    var row = [];

    Object.keys(transaction).forEach(function (field) {
      switch (field) {
        case 'CODE':
          return row.push(transaction.CODE);
        case 'PRICE':
          return row.push(transaction.PRICE);
        case 'QTY':
          return row.push(transaction.QTY);
        default:
          return row.push('');
      }
    });
    return { values: row };
  });
}

And then you can test it like this:

function test() {
  const testData = [
    {CODE:1,PRICE:1,QTY:1},
    {CODE:2,PRICE:2,QTY:2},
    {CODE:3,PRICE:3,QTY:3},
    {CODE:4,PRICE:4,QTY:4},
  ];
  Logger.log(responseToRows(testData));
}
// Result:
//[{values=[1.0, 1.0, 1.0]}, 
// {values=[2.0, 2.0, 2.0]}, 
// {values=[3.0, 3.0, 3.0]}, 
// {values=[4.0, 4.0, 4.0]}
//]

Also, if you plan to write that result to a sheet, then it's probably better to have it in a 2-dimension array format, so you'd have to change return { values: row }; to just return row;.

Upvotes: 1

Related Questions