JSON returning multidimensional arrays from cryptcompare api - json

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.

Related

JSON import - Cannot read property 'length' of undefined

I'm trying to import JSON via API into Google sheets but get the error
Cannot read property 'length' of undefined
Here is my code
function importRank(){
url = 'https://public-api.solscan.io/token/holders?tokenAddress=sinjBMHhAuvywW3o87uXHswuRXb3c7TfqgAdocedtDj&offset=0&limit=max'
var json = JSON.parse(UrlFetchApp.fetch(url).getContentText())
var data = json.data.owner
var data2 = json.data.rank
var data3 = json.data.total
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('WalletRank')
sh.getRange(2,1,data.length,data[0].length).setValues(data)
sh.getRange(2,2,data2.length,data2[0].length).setValues(data2)
sh.getRange(2,3,data3.length,data3[0].length).setValues(data3)
}
Try
function importRank(){
url = 'https://public-api.solscan.io/token/holders?tokenAddress=sinjBMHhAuvywW3o87uXHswuRXb3c7TfqgAdocedtDj&offset=0&limit=max'
var json = JSON.parse(UrlFetchApp.fetch(url).getContentText())
var data=[]
Logger.log(json.total)
json.data.forEach(function(x){
data.push([x.owner,x.rank,x.amount])
})
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('WalletRank')
sh.getRange(2,1,data.length,data[0].length).setValues(data)
sh.getRange(2,4).setValue(json.total)
}
Explanation
the structure is as follows
{"data":[
{"address":"__________","amount":________,"decimals":__,"owner":"___","rank":_},
...
],"total":_____}
that means that data is an array [] of multi elements which contains each of them {} address, amount, decimals, owner and rank
Reference
forEach

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]);
}

JIVE API GET request returns null for values

I can't seem to access any of the values in my Jive API response. This is what I've got so far, which works. I just need to get the values, but seem to be returning null every time I try to access them. When I iterate the object, I can access the value of the allocated space, ie. single characters as opposed to the value of a key. Please help!
function include(filename) {
var finalRequest = UrlFetchApp.fetch('https://www.cloudconnect.xxx...);
var data = finalRequest.toString().replace("throw 'allowIllegalResourceCall is false.';",
"").trim();
for(i in data){
Logger.log(data);
}
}
If you want to retrieve the key and values by parsing the response value from the URL, how about the following modification?
Modified script:
function include(filename) {
var finalRequest = UrlFetchApp.fetch('https://www.cloudconnect.goog/api/core/v3/contents?count=5&fields=subject,content,links.next');
var data = finalRequest.toString().replace("throw 'allowIllegalResourceCall is false.';", "").trim();
data = JSON.parse(data); // Added
for (var i in data) {
Logger.log("key: %s, value: %s", i, data[i]); // Modified
}
}
In your case, you can also use var data = finalRequest.getContentText().replace("throw 'allowIllegalResourceCall is false.';", "").trim(); instead of var data = finalRequest.toString().replace("throw 'allowIllegalResourceCall is false.';", "").trim();.
References:
JSON.parse()
for...in
getContentText()
If I misunderstood your question and this was not the direction you want, I apologize.

Google Apps Script messing up JSON values

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;
}