Alberto Garcia
Alberto Garcia

Reputation: 11

Append only unique rows

I am trying to read an external JSON API and write parsed values from it into google sheet. So each API call writes a new row into the sheet. The second requirement is to write the row only if it contains something else than already inserted rows - in other words append new row only if it is unique.

I've finished the first requirement. I've used JSON.parse and appendRow and it works with no problem.

Unfortunately, I cannot get thru the second requirement. I can not figure any construction nor find an example solution.

Does anybody have an advice how to append only unique rows from google apps script?

EDIT: My apologize for the above inexact post. Here are the details.

Below mentioned code is my solution for the first requirement:

function run() {

 var data = UrlFetchApp.fetch("https://url/json-api").getContentText();
 var json = JSON.parse(data);

 var last = (json.last);
 var credit = parseInt(json.credit); 

 var doc = SpreadsheetApp.openById("googleSheetID");
 var list = doc.getSheets()[0];


 list.appendRow([last, credit]);
}

So it simply append new row each time I run the script. Unfortunately, the returned JSON changes only from time to time. When I scheduled the script to run every 5 minutes it leads to many redundant rows.

However I don't want to run any kind of distinct after the redundant rows are written. I'd like to check if the new parsed data is unique and if so - write, otherwise nothing.

Upvotes: 1

Views: 385

Answers (1)

TheMaster
TheMaster

Reputation: 50452

  • getLastRow's value and check whether it's equal to last/credit. Then appendRow, if needed.

  • Script Sample Snippet:

    var lastRow=list.getRange(1,list.getLastRow(),1,2).getValues(); //[[prev.last,prev.credit]]
    if(lastRow[0][0]!=last && lastRow[0][1]!=credit){
     list.appendRow([last, credit]);
    }
    

Upvotes: 1

Related Questions