Google Apps Script messing up JSON values - json

I´m using a Google Apps Script, trying to import Bitcoin-exchange rate information to a Google Spreadsheet. I use this code:
var url = "https://btc-e.com/api/2/btc_usd/ticker";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var lcharts_data = JSON.parse(json)
function bitcoin(){
var b = lcharts_data["ticker"]["avg"];
return b;
}
The JSON-file looks like this:
{"ticker":
{"high":947.99902,
"low":817.64001,
"avg":882.819515,
"vol":24625847.06001,
"vol_cur":28189.09956,
"last":930,
"buy":930,
"sell":929.998,
"updated":1385575341,
"server_time":1385575342}
}
}
Yet b returns as 22.49. What am i doing wrong?

I use the similar method for receiving the data but I parse it slightly different. For example:
var url = "https://btc-e.com/api/2/btc_usd/ticker";
var response = UrlFetchApp.fetch(url);
var json = response.toString();
var lcharts_data = JSON.parse(json);
Notice the toString() method and the native Utilities.jsonParse() method. I tried JSON.parse() but that didn't work for me.
Also are using an API key to access the data? Have tried above but it's timing out.

As at when I tested your url, the JSON response returned was:
{
"ticker":{
"high":421.70001,
"low":418,
"avg":419.850005,
"vol":2361935.91952,
"vol_cur":5620.41595,
"last":420.168,
"buy":420.168,
"sell":419.853,
"updated":1460626271,
"server_time":1460626273
}
}
Here's the code that returns the value for 'avg':
var url = "https://btc-e.com/api/2/btc_usd/ticker";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var lcharts_data = JSON.parse(json);
function bitcoin(){
var b = lcharts_data.ticker.avg;
return b;
}

Related

Get company name in google sheets using stock ticker

I have a google sheet getting stock information by symbol. I found this code below to get prices but don't really understand how it's working.
function yahooF(ticker) {
const url = `https://finance.yahoo.com/quote/${ticker}?p=${ticker}`;
const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
const contentText = res.getContentText();
const price = contentText.match(/<fin-streamer(?:.*?)data-test="qsp-price"(?:.*)>(\d+\.\d+)<\/fin-streamer>/);
console.log(price[1]);
return price[1];
}
Does anyone know a way using a similar method to get specifically the company name, but understanding how to use this to get other data would be great. I'm not interested in using =GOOGLEFINANCE functions as they seem to fail pretty often.
Try, by parsing the json inside the source
function yahooFNameOfCompany(ticker) {
const url = `https://finance.yahoo.com/quote/${ticker}?p=${ticker}`;
const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true}).getContentText();
var jsonString = res.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString)
console.log(data.context.dispatcher.stores.StreamDataStore.quoteData[ticker].shortName)
}

Google Sheet Script - Function should return a JSON data but brings NULL

I'm trying to get a value from a JSON object from a URL for use in a Google Sheet.
This is the script:
function getPricefromExchange() {
var url = 'https://api.coinstats.app/public/v1/tickers?exchange=binance&pair=DOT-USDT';
var reponse = UrlFetchApp.fetch(url);
var json = reponse.getContentText();
var data = JSON.parse(json);
return data.tickers.price;
}
The JSON data is as follows:
{
"tickers":
[
{ "from":"DOT",
"to":"USDT",
"exchange":"Binance",
"price":27.82}
]
}
The return of my function is NULL and however I change the return value (e.g.return data.price; or return data;) the return value stays at NULL.
What did I do wrong? I just want to have the price as return value.
Try
function test(){
var url = 'https://api.coinstats.app/public/v1/tickers?exchange=binance&pair=DOT-USDT';
var reponse = UrlFetchApp.fetch(url);
var json = reponse.getContentText();
var data = JSON.parse(json);
Logger.log(data.tickers[0].price)
}
as you can see, tickers is not a parent, tickers is an array [] (with one element)

Google script - parse json response

This is the json response (from my multiple choice field jsfiddle) that i'm trying to parse:
{"selected":true,"disabled":false,"text":"Ctr","id":"Ctr","title":"","_resultId":"select2-selectcountry-result-je97-Ctr","element":{}},
{"selected":true,"disabled":false,"text":"Title
Part1","id":"TitlePart1","title":"","_resultId":"select2-selectcountry-result-uv7s-TitlePart1","element":{}},
{"selected":false,"disabled":false,"text":"Milan","id":"Milan","_resultId":"select2-selectcountry-result-bmba-Milan","element":{}}]
I need to get: {"id":value},{"id":value},{"id":value} ...
{id:Ctr},{"id":"TitlePart1"},{"id":"Milan} ...
To achieve this result, I'm using this code:
var response = (JSON.stringify($('#selectcountry').select2('data')) );
var json = JSON.parse(response);
var dataSet = json;
var row = [],
data;
for(var i in json){
data = dataSet[i];
row.push({'id': json[i].id})
}
sheet.getRange(6,1).setValue(row);
But in this way I get only the first id:value:
{id:Ctr}
Any help?
Thanks
var s='[{"selected":true,"disabled":false,"text":"Ctr","id":"Ctr","title":"","_resultId":"select2-selectcountry-result-je97-Ctr","element":{}},{"selected":true,"disabled":false,"text":"Title Part1","id":"TitlePart1","title":"","_resultId":"select2-selectcountry-result-uv7s-TitlePart1","element":{}},{"selected":false,"disabled":false,"text":"Milan","id":"Milan","_resultId":"select2-selectcountry-result-bmba-Milan","element":{}}]';
function findId() {
var d=JSON.parse(s);
var ids=[];
d.forEach(function(o){
ids.push(o.id);
});
Logger.log(ids);
//Add this
SpreadsheetApp.getActiveSheet().getRange(1,1,1,3).setValues([ids]);
}

JSON returning multidimensional arrays from cryptcompare api

I have been trying to figure out how to get data from JSON from cryptocompare api to google spreadsheet.Here it's my code:
function gather(symbol, array) {
for (i in array.AggregatedData) {
return array[i];
}
return 0;
}
function chc(symbol, key, rand) {
var url = "https://www.cryptocompare.com/api/data/coinsnapshot/?fsym="+ symbol +"&tsym=USD";
var response = UrlFetchApp.fetch(url);
var text = response.getContentText();
var obj_array = JSON.parse(text);
var obj = gather(obj_array);
var value = obj[key];
return parseFloat(value);
}
I get an error that cannot read the property of AggregatedData undefined.
Here it's the way the data shows on the api
JSON output
You might have a wrong variable type.
If AggregatedData is method or function you should use () at the end.
PS: There is a script from Trevor Lohrbeer that can be used to import JSON more intuitively.

Google Sheets JSON Parse Loop Action

Worksheet Link: https://docs.google.com/spreadsheets/d/1MLlKnlS-IB0OwWGIJ9tVI38pvqoCktd1HKlpofzn8cI/edit?usp=sharing
Hello all. I am new to JSON parsing within GAS and hope someone can help. It seems like it should be something fairly simple, but I cant figure it out.
The JSON contains 2 properties that I am trying to extract, case_upc_14 and salsify:created_at. I am able to successfully extract individual values, but I need help creating a loop to extract all case_upc_14 and salsify:created_at properties and return the values on the export tab.
This is what I have, any assistance would be greatly appreciated.
function parse() {
var s = SpreadsheetApp.getActiveSpreadsheet();
var t = s.getSheetByName('Sheet2');
var response = UrlFetchApp.fetch('https://salsify-dandelion.s3-external-1.amazonaws.com/1/3889/user_data_export/1/2017/09/24/15%3A56%3A46-e227b249/export.json?response-content-disposition=attachment%3B%20filename%3D%22product-feed.json%22&response-content-type=application%2Fjson&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJSAUHNZHZGLUDXDA%2F20170924%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20170924T160544Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=b9407a842978363265472d27f4e8026506ef7d0a7e859a7c39feb0f4870fb9ad');
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data[4]['products'][1]['case_upc_14']);
Logger.log(data[4]['products'][1]['salsify:created_at']);
}
How about following modification? It seems that you try to import the retrieved data to Spreadsheet. So the modified script retrieves case_upc_14 and salsify:created_at, and imports the data to Sheet2 of Spreadsheet.
Modified script :
function parse() {
var s = SpreadsheetApp.getActiveSpreadsheet();
var t = s.getSheetByName('Sheet2');
var response = UrlFetchApp.fetch('https://salsify-dandelion.s3-external-1.amazonaws.com/1/3889/user_data_export/1/2017/09/24/15%3A56%3A46-e227b249/export.json?response-content-disposition=attachment%3B%20filename%3D%22product-feed.json%22&response-content-type=application%2Fjson&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJSAUHNZHZGLUDXDA%2F20170924%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20170924T160544Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=b9407a842978363265472d27f4e8026506ef7d0a7e859a7c39feb0f4870fb9ad');
var json = response.getContentText();
var data = JSON.parse(json);
var ar = [];
data[4].products.forEach(function(e) {
ar.push([e['salsify:created_at'], e['case_upc_14']])
});
t.getRange(1,1,ar.length,ar[0].length).setValues(ar);
}
If I misunderstand your question, I'm sorry.