Fetch json API data from GDAX - json

I'm trying to get the BTC-EUR ticker from GDAX site to Google Spreadsheet using a script. I got this code but it doesn't work, always returning me error: The coordinates or dimensions of the range are invalid.
var baseUrl = 'https://api.gdax.com';
var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GDAX");
function ticker() {
var request = "/products/btc-eur/ticker";
var requestUrl = baseUrl + request;
var response = UrlFetchApp.fetch(requestUrl);
var json = JSON.parse(response.getContentText());
var rows = [],
jsondata;
for (i = 0; i < json.length; i++) {
jsondata = json[i];
rows.push([jsondata.price]);
}
dataRange = data.getRange(14, 1, rows.length, 1);
dataRange.setValues(rows);
}
I'm using the same code to push my balance to the spreadsheet, and it is working. I cannot understand why this one return me the error. If I log the json var I get the correct values from the site.
Anyone can help? Thank you

How about a following modification?
Modification points :
The JSON data from https://api.gdax.com/products/btc-eur/ticker is as follows. In this data, the value of price is only one. So when the JSON data is always like this, you can directly retrieve the value using json.price.
{
"trade_id": 4314549,
"price": "3691.06000000",
"size": "0.00004053",
"bid": "3691",
"ask": "3691.05",
"volume": "945.78845044",
"time": "2017-01-01T00:00:00.000000Z"
}
When this is reflected to your script, the modified script is as follows.
Modified script :
function ticker() {
var baseUrl = 'https://api.gdax.com';
var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GDAX");
var request = "/products/btc-eur/ticker";
var requestUrl = baseUrl + request;
var response = UrlFetchApp.fetch(requestUrl);
var json = JSON.parse(response.getContentText());
var rows = [[json.price]];
var dataRange = data.getRange(14, 1, 1, 1);
dataRange.setValue(rows);
}
If I misunderstand your question, I'm sorry.

Related

Get specific data from Salesbinder API JSON to a Google sheet

Hi what I'm trying to do is get the data from a Salesbinder invoice API (Invoice # is taken from Sheet2 Cell A1) output the data to a Google sheet (sheet Cell A2)
here's the code i'm using to get data from Salesbinder API
function fetching() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var sheet2 = ss.getSheetByName('Sheet2');
var InvNumber = sheet2.getRange('A1').getValue();
var USERNAME = 'APIKey';
var PASSWORD = 'x';
var url = 'https://mydomain.salesbinder.com/api/2.0/documents.json?documentNumber='+InvNumber+'&contextId=5';
var headers = {
"Authorization": "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};
let response = UrlFetchApp.fetch(url, { headers });
Logger.log(response.getContentText());
}
The result I get from the data is like this
{"document":[{"document_number":8542,"name":"VIOLET BEARINGS","context_id":5,"total_cost":7213.03,"total_tax":415.45,"total_tax2":0,"total_price":8309.08,"total_transactions":0,"issue_date":"2022-12-13T00:00:00+00:00","expiry_date":null,"shipping_address":"(Same as above)","date_sent":null,"shipped_percent":null,"status_id":9,"public_note":"","attention":"GLEN","payment_terms":"","id":"0b24e8d2-e7cc-4441-abd7-337c8a2c6cf1","customer_id":"5b0d881b-6a88-46e5-998c-06330a8e0006","user_id":"5b0d75b3-e9cc-4899-bf99-77610a8e0006","associated_document_id":"","created":"2022-12-13T21:21:43+00:00","modified":"2022-12-21T16:01:04+00:00","status":{"id":9,"name":"unpaid"},"context":{"id":5,"name":"invoice"},"customer":{"id":"5b0d881b-6a88-46e5-998c-06330a8e0006","name":"TestClient","customer_number":1889,"billing_address_1":"Add1","billing_address_2":"Add2","billing_city":"TestCity","billing_region":"TestLoc","billing_postal_code":"TestPost","billing_country":"CANADA","shipping_address_1":"Add1","shipping_address_2":"Add2","shipping_city":"TestCity","shipping_region":"TestLoc","shipping_postal_code":"TestPost","shipping_country":"CANADA"},"user":{"first_name":"test","last_name":"test"},"document_items":[{"id":"0ea11906-f197-4eb4-971e-715d4dc77ab2","name":"B-0832","document_id":"0b24e8d2-e7cc-4441-abd7-337c8a2c6cf1","item_id":null,"unit_id":4,"service_category_id":"5dc2f6d2-27e0-4dac-a2b7-39080a8e0008","description":"JGE/H/K DOOR GASKET","quantity":8,"quantity_partially_received":0,"quantity_partially_shipped":0,"tax":5,"tax2":0,"discount_percent":0,"cost":38.1,"price":43.81,"discounted_price":0,"weight":2,"modified":"2022-12-21T16:01:04+00:00","created":"2022-12-15T15:43:57+00:00","item_variations_location_id":null,"item_variation_data":null,"delete":false,"item":null},{"id":"2b7e9376-ed70-4e75-95c9-6237aad8cfc0","name":"B-0770","document_id":"0b24e8d2-e7cc-4441-abd7-337c8a2c6cf1","item_id":null,"unit_id":4,"service_category_id":"5dc2f6d2-27e0-4dac-a2b7-39080a8e0008","description":"MAIN BEARING JGE/H/K","quantity":8,"quantity_partially_received":0,"quantity_partially_shipped":0,"tax":5,"tax2":0,"discount_percent":0,"cost":282.73,"price":325.14,"discounted_price":0,"weight":6,"modified":"2022-12-21T16:01:04+00:00","created":"2022-12-15T15:43:57+00:00","item_variations_location_id":null,"item_variation_data":null,"delete":false,"item":null},{"id":"391c2ec1-e02d-4390-9a10-429c2ea460fc","name":"B-2082","document_id":"0b24e8d2-e7cc-4441-abd7-337c8a2c6cf1","item_id":null,"unit_id":4,"service_category_id":"5dc2f6d2-27e0-4dac-a2b7-39080a8e0008","description":"ROD BEARING JGE/H/K","quantity":8,"quantity_partially_received":0,"quantity_partially_shipped":0,"tax":5,"tax2":0,"discount_percent":0,"cost":282.73,"price":325.14,"discounted_price":0,"weight":5,"modified":"2022-12-21T16:01:04+00:00","created":"2022-12-15T15:43:57+00:00","item_variations_location_id":null,"item_variation_data":null,"delete":false,"item":null},{"id":"725fb97d-243f-44aa-98d0-50d903871ae4","name":"B-0776","document_id":"0b24e8d2-e7cc-4441-abd7-337c8a2c6cf1","item_id":null,"unit_id":4,"service_category_id":"5dc2f6d2-27e0-4dac-a2b7-39080a8e0008","description":"THRUST PLATE JGE/H/K","quantity":2,"quantity_partially_received":0,"quantity_partially_shipped":0,"tax":5,"tax2":0,"discount_percent":0,"cost":878.44,"price":1010.21,"discounted_price":0,"weight":7,"modified":"2022-12-21T16:01:04+00:00","created":"2022-12-15T15:43:57+00:00","item_variations_location_id":null,"item_variation_data":null,"delete":false,"item":null},{"id":"956cf37e-3921-4cad-94bf-670cdedd2d17","name":"B-1032","document_id":"0b24e8d2-e7cc-4441-abd7-337c8a2c6cf1","item_id":null,"unit_id":4,"service_category_id":"5dc2f6d2-27e0-4dac-a2b7-39080a8e0008","description":"JGK DOOR GASKET","quantity":8,"quantity_partially_received":0,"quantity_partially_shipped":0,"tax":5,"tax2":0,"discount_percent":0,"cost":17.21,"price":19.79,"discounted_price":0,"weight":3,"modified":"2022-12-21T16:01:04+00:00","created":"2022-12-15T15:43:57+00:00","item_variations_location_id":null,"item_variation_data":null,"delete":false,"item":null},{"id":"c2b74c55-465b-4bee-84a1-6c9e8e5bd102","name":"A-0661","document_id":"0b24e8d2-e7cc-4441-abd7-337c8a2c6cf1","item_id":null,"unit_id":4,"service_category_id":"5dc2f6d2-27e0-4dac-a2b7-39080a8e0008","description":"OIL FILTER","quantity":3,"quantity_partially_received":0,"quantity_partially_shipped":0,"tax":5,"tax2":0,"discount_percent":0,"cost":24.5,"price":28.18,"discounted_price":0,"weight":4,"modified":"2022-12-21T16:01:04+00:00","created":"2022-12-15T15:43:57+00:00","item_variations_location_id":null,"item_variation_data":null,"delete":false,"item":null},{"id":"de2c8695-9589-4856-be7a-d3979a776646","name":"FREIGHT CHARGE","document_id":"0b24e8d2-e7cc-4441-abd7-337c8a2c6cf1","item_id":null,"unit_id":1,"service_category_id":"5e6a78e2-cf6c-437c-ac52-0c3a0a8e000a","description":"RE:E2920103","quantity":1,"quantity_partially_received":0,"quantity_partially_shipped":0,"tax":5,"tax2":0,"discount_percent":0,"cost":70.64,"price":95.35,"discounted_price":0,"weight":8,"modified":"2022-12-21T16:01:04+00:00","created":"2022-12-21T15:34:51+00:00","item_variations_location_id":null,"item_variation_data":null,"delete":false,"item":null},{"id":"eab3c271-20ce-4c4e-af92-8553425eaa71","name":"C-6200","document_id":"0b24e8d2-e7cc-4441-abd7-337c8a2c6cf1","item_id":null,"unit_id":4,"service_category_id":"5dc2f6d2-27e0-4dac-a2b7-39080a8e0008","description":"TOP COVER GASKET","quantity":1,"quantity_partially_received":0,"quantity_partially_shipped":0,"tax":5,"tax2":0,"discount_percent":0,"cost":345.85,"price":397.73,"discounted_price":0,"weight":1,"modified":"2022-12-21T16:01:04+00:00","created":"2022-12-13T21:21:43+00:00","item_variations_location_id":null,"item_variation_data":null,"delete":false,"item":null}]}]}
I would like to output the JSON content to look like this on my google sheet
https://docs.google.com/spreadsheets/d/18x1cyztf5SgnKZHjqgWx2iP7SzQAksOzE_EVZoUOcy8/edit#gid=0
Any help would be greatly appreciated
Thanks
In your script, when the value of response.getContentText() is your showing data, how about the following modification?
From:
Logger.log(response.getContentText());
To:
Logger.log(response.getContentText());
// I added the below script.
const value = JSON.parse(response.getContentText());
const addValues = [value.document[0].customer.name, value.document[0].issue_date, value.document[0].attention, value.document[0].name];
const res = value.document[0].document_items.map(o => [value.document[0].document_number, ...["name", "description", "quantity", "price", "discounted_price"].map(h => o[h]), ...addValues]);
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
sheet.getRange(sheet.getLastRow() + 1, 1, res.length, res[0].length).setValues(res);
Please set your sheet name to getSheetByName("Sheet1").
Unfortunately, I cannot find External PO# you expect from your data.
Suggestion: Clean and Extract the Required Data
The first thing I noticed is that your current script has already extracted a single JSON object from Salesbinder. However, the format returned is hard to read. You may use JSON beautify sites online to rearrange and analyze the JSON object you have produced like JSON Viewer (DISCLAIMER: I am not affiliated with the website, I just find it helpful to share it to others due to its helpful features).
Script
Afterwards, you may be able to access the data you wanted by accessing the JSON object. For your table, you may use the following:
var salesBinderInvoiceNumVal = object.document[0].document_number;
var itemNameVal = object.document[0].document_items[0].name;
var descriptionVal = object.document[0].document_items[0].description;
var quantityVal = object.document[0].document_items[0].quantity;
var priceVal = object.document[0].document_items[0].price;
var discountPercentVal = object.document[0].document_items[0].discount_percent;
var clientNameVal = object.document[0].customer.name;
var issueDateVal = object.document[0].issue_date;
var attentionVal = object.document[0].attention;
var nameVal = object.document[0].name;
Note: The External PO number can't be found since there are no given values in your sample table.
But before doing so, you may want to store the generated JSON object to a variable. Thus, you may change:
Logger.log(response.getContentText());
to:
var object = response.getContentText();
Afterwards, you may add the setValues() function to add the values to the last row of your table. Thus, your script should be somewhat like this:
function fetching() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var sheet2 = ss.getSheetByName('Sheet2');
var InvNumber = sheet2.getRange('A1').getValue();
var USERNAME = 'APIKey';
var PASSWORD = 'x';
var url = 'https://mydomain.salesbinder.com/api/2.0/documents.json?documentNumber=' + InvNumber + '&contextId=5';
var headers = {
"Authorization": "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};
let response = UrlFetchApp.fetch(url, { headers });
//Changes start here
var object = response.getContentText(); //Store the JSON object to this variable
var lastRow = sheet.getLastRow(); //get the last row
//required values
var salesBinderInvoiceNumVal = object.document[0].document_number;
var itemNameVal = object.document[0].document_items[0].name;
var descriptionVal = object.document[0].document_items[0].description;
var quantityVal = object.document[0].document_items[0].quantity;
var priceVal = object.document[0].document_items[0].price;
var discountPercentVal = object.document[0].document_items[0].discount_percent;
var clientNameVal = object.document[0].customer.name;
var issueDateVal = object.document[0].issue_date;
var attentionVal = object.document[0].attention;
var nameVal = object.document[0].name;
//add the required values to a 2d array
var output = [[salesBinderInvoiceNumVal, itemNameVal, descriptionVal, quantityVal, priceVal, discountPercentVal, clientNameVal, issueDateVal, attentionVal, nameVal]];
sheet.getRange(lastRow+1, 1, 1, output[0].length).setValues(output); //add the 2d array to the last row of your table
}
Output:
Since your script only gets the value of one cell, I assumed that it only fetches one item or one row to your table. NOTE: I only processed the given JSON object in your post since I have no access/account in Salesbinder. I did assume that it was the output of your current script.
Reference:
You may further study about accessing JSON objects date in this article: JSON Object Literals

TypeError: Cannot read property '0' of undefined (Google Sheets / App Script)

I would like to know what I need to adjust in the script so that the results appear in the spreadsheet:
TypeError: Cannot read property '0' of undefined (line 7)
function Cartola() {
var url = "https://api.cartolafc.globo.com/mercado/destaques";
var response = UrlFetchApp.fetch(url);
var data = response.getContentText();
var result = JSON.parse(data);
var apelido = result.Atleta[0].apelido;
var foto = result.Atleta[0].foto;
var clube_nome = result.Atleta[0].clube_nome;
var posição = result.Atleta[0].posicao;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear()
var headerRow = ['apelido','foto','clube_nome','posição'];
sheet.appendRow(headerRow);
for(var i=0;i<result[0].Atleta;i++){
var row = [result.Atleta[i].apelido,result.Atleta[i].foto,result.Atleta[i].clube_nome,result.Atleta[i].posicao];
SpreadsheetApp.getActiveSheet().appendRow(row);
}
}
data is an array, so you need to access the element first:
var apelido = result[0].Atleta.apelido;
I think you're trying to print every player to spreadsheet, but what you've written is only looking at one of the players. Please first look at the data returned by the API and understand its structure. Looks something like this:
[
{
"Atleta": {
"atleta_id": 68952,
"nome": "Mário Sérgio Santos Costa",
"apelido": "Marinho",
"foto": "https://s.glbimg.com/es/sde/f/2019/05/30/cd8a7f9b0744e105efa0a0c572d37d6f_FORMATO.png",
"preco_editorial": 5
},
"escalacoes": 996124,
"clube": "SAN",
"clube_nome": "Santos",
"clube_id": 277,
"escudo_clube": "https://s.glbimg.com/es/sde/f/organizacoes/2014/04/14/santos_60x60.png",
"posicao": "Atacante",
"posicao_abreviacao": "ATA"
}
]
Once you understand the data, then consider this modified script, which uses batch operations to run much more quickly.
function Cartola() {
var url = 'https://api.cartolafc.globo.com/mercado/destaques';
var response = UrlFetchApp.fetch(url);
var results = JSON.parse(response.getContentText());
var table = [['apelido','foto','clube_nome','posição']];
for (var i = 0; i < results.length; i++) {
var r = results[i];
var apelido = r.Atleta.apelido;
var foto = r.Atleta.foto;
var clube_nome = r.clube_nome;
var posição = r.posicao;
table.push([apelido, foto, clube_nome, posição]);
}
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear().getRange(1, 1, table.length, table[0].length).setValues(table);
}

How to transform the JSON response into a table in sheets

I'm sending a request to an API (in a Google Scripts), and I'm getting the response as a JSON text that looks like this:
[{"id":26319355,"name":"1. WAW -FIRST SESION","calendar":"Glovers
Click&Collect","duration":30,"isSeries":false,"slots":90,"slotsAvailable"
:89,"color":"#E3DE7D","price":"0.00","category":"WAW","description":"",
"calendarID":2978881,"serviceGroupID":2978881,"appointmentTypeID":10104780,
"calendarTimezone":"Europe\/Madrid","time":"2019-06-01T12:00:00+0200",
"localeTime":"June 1, 2019 12:00"},
{"id":26466803,"name":"1. WAW -FIRST SESION","calendar":"Glovers
Click&Collect","duration":30,"isSeries":false,"slots":90,"slotsAvailable"
:89,"color":"#E3DE7D","price":"0.00","category":"WAW","description":"",
"calendarID":2978881,"serviceGroupID":2978881,"appointmentTypeID":10104780,
"calendarTimezone":"Europe\/Madrid","time":"2019-06-07T14:00:00+0200",
"localeTime":"June 7, 2019 14:00"},
I want to paste this response as a table in my spreadsheet.
My script actually looks like this (where response is the response I get from the API request):
function CheckAv(row,acuityid,check,url,apiusername,apisecretkey,ss) {
var header = {
"contentType": "application/json",
"headers":{"Authorization" : " Basic " + Utilities.base64Encode(apiusername + ":" + apisecretkey)},
"method" : "GET"
}
muteHttpExceptions: true
var response = UrlFetchApp.fetch(url, header);
var data = JSON.parse(response.getContentText());
var text = response.getResponseCode();
Logger.log(text);
}
I assume it will be really easy but I can't find the solution.
You can cycle through your JSON structure and push each key and value to a specified row using the code below.
json = [{your: "JSON", data: "goes"}, {in : "here"}]
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet = ss.getActiveSheet();
var rows = [],
data;
for (i = 0; i < json.length; i++) {
for (j in json[i]) {
dataq = json[i][j];
Logger.log(dataq);
rows.push([j, dataq]);
}
dataRange = sheet.getRange(1, 1, rows.length, 2);
dataRange.setValues(rows);
}

Fetch API data from Bittrex

I'm trying to fetch the API data with Google Apps Script about my balance on Bittrex but it returns me nothing, no errors and only blank cells. This is the code I've written based on the documentation here: https://bittrex.com/Home/Api
function getBalance() {
var ss = SpreadsheetApp.openById("***");
var data = ss.getSheetByName("Data");
var key = ss.getSheetByName("Api").getRange('A2').getValue();
var secret = ss.getSheetByName("Api").getRange('B2').getValue();
var baseUrl = 'https://bittrex.com/api/v1.1/';
var nonce = Math.floor(new Date().getTime()/1000);
var command = "/account/getbalances";
var uri = baseUrl.concat(command + "?apikey=" + key + "&nonce=" + nonce);
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512,
uri,
secret);
signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('')
var headers = {
"apisign": signature
}
var params = {
"method": "get",
"headers": headers,
}
var response = UrlFetchApp.fetch(uri, params);
var json = JSON.parse(response.getContentText());
var blnc = [];
blnc.push(['Balance']);
for(var key in json.result)
{
blnc[0].push(json.result[key]);
}
askRange = data.getRange(2, 2, blnc.length, 1);
askRange.setValues(blnc);
}
The askrange last number is "1" because the script only pass the "Balance" value to the spreadsheet, but the values should be something around 210. Any help? Thank you
I solved it, the problem was in the "command" variable, there was a slash not needed that generated an url with a double slash

Google App Script - The web app URL response is "Hello, world" instead of JSON

I am trying to learn google app script, hence I started with "Hello, World". Eventually, i borrowed a working code to return a JSON for data saved in speadsheet. Below is the code -
function doGet(e) {
var json = convertSheet2JsonText();
return ContentService.createTextOutput(JSON.stringify(json))
.setMimeType(ContentService.MimeType.JSON);
}
function convertSheet2JsonText() {
var sheet =
SpreadsheetApp.openById("1kQVRu_9HLAZZWReGxGQL3513ShiwUQ6Ux-
GkjO19nWQ").getActiveSheet();
var colStartIndex = 1;
var rowNum = 1;
var firstRange = sheet.getRange(1, 1, 1, sheet.getLastColumn());
var firstRowValues = firstRange.getValues();
var titleColumns = firstRowValues[0];
// after the second line(data)
var lastRow = sheet.getLastRow();
var rowValues = [];
for(var rowIndex=2; rowIndex<=lastRow; rowIndex++) {
var colStartIndex = 1;
var rowNum = 1;
var range = sheet.getRange(rowIndex, colStartIndex, rowNum,
sheet.getLastColumn());
var values = range.getValues();
rowValues.push(values[0]);
}
// create json
var jsonArray = [];
for(var i=0; i<rowValues.length; i++) {
var line = rowValues[i];
var json = new Object();
for(var j=0; j<titleColumns.length; j++) {
json[titleColumns[j]] = line[j];
}
jsonArray.push(json);
}
return jsonArray ;
}
I have followed the steps to deploy it as a web-app.
1. When I use the "Latest Code" link to test the code, I get expected JSON.
2. However, I use the link to "Current Web App URL", I get text "Hello World".
I created a new spreadsheet and copied the same code in script editor and deployed it as a web app. Now if I use the link "Current Web App URL", I get intended JSON.
Please let me know, in first case how can I make the prod link to send JSON instead of string "Hello World".
Please let me know in case of any questions.
I changed the version and it worked.