Google script - parse json response - google-apps-script

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

Related

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)

How to Import JSON data to google sheet with for loop

I almost import my JSON data from API.
But I don't know what is exactly the value of setvalue() in my case.
I want to get a google sheet of the product list loop automatically.
The final output that I want to get is the product list continually looping from page 1 to the last page.
When I run my code on Apps script, I got the output like the screenshot below.
But, It repeats only the first product of the product list.
function dearAPI(endpoint,sheetname,dig) {
const dataRows = [];
let pagenumber = 1;
const a = UrlFetchApp.fetch(
'https://inventory.dearsystems.com/externalapi/v2/product?page=1&limit=10',
{
'method':'get',headers:
{
"api-auth-accountid": accountID,
"api-auth-applicationkey": secret,
},
"contentType": 'application/json'
});
var sheet = SpreadsheetApp.getActiveSheet();
var json = JSON.parse(a.getContentText());
var headers = [Object.keys(json.Products[0])];
sheet.getRange(1,1,headers.length,headers[0].length).setValues(headers);
for(var i = 0; i < json.Products.length; i++){
var rows = [Object.values(json.Products[i])];
var final = Object.values(json.Products[i]);
getFinal = [final[i]];
for (var j = 0; j < json.Products.length; j++){
sheet.getRange(2, i+1, json.Products.length, rows[0].length).setValue(getFinal);
}
}
}
Suggestion:
Assuming this manually created sample JSON below has the same JSON structure from your API:
{
Products=[
{
Name=DarknessPumpLarge,
DropShipMode=NoDropShip,
Brand=Darkness,
DefaultLocation=Toronto,
Category=Accessories,
CostingMethod=FIFO,
Type=Stock
},
{
DropShipMode=NoDropShip,
Name=AppleiPhone,
Type=Stock,
DefaultLocation=California,
Category=Gadget,
Brand=Apple,
CostingMethod=FIFO
},
{
CostingMethod=FIFO,
Brand=Samsung,
DropShipMode=NoDropShip,
DefaultLocation=SouthKorea,
Name=SamsungGalaxyS21,
Category=Gadget,
Type=Stock
}
]
}
NOTE: It would also be better if you can share a snippet of your JSON value for better replication.
You can try this implementation, the script starting from the line with var = headers:
function dearAPI() {
var getFinal = []; //Assuming the `getFinal` was initialized as `an array variable
//Sample JSON value manually imputted here for replication
const json = {
"Products":[
{"Name":"Darkness Pump Large", "Category":"Accessories", "Brand":"Darkness", "Type":"Stock", "CostingMethod":"FIFO", "DropShipMode":"No Drop Ship", "DefaultLocation":"Toronto"},
{"Name":"Apple iPhone", "Category":"Gadget", "Brand":"Apple", "Type":"Stock", "CostingMethod":"FIFO", "DropShipMode":"No Drop Ship", "DefaultLocation":"California"},
{"Name":"Samsung Galaxy S21", "Category":"Gadget", "Brand":"Samsung", "Type":"Stock", "CostingMethod":"FIFO", "DropShipMode":"No Drop Ship", "DefaultLocation":"South Korea"}
]
}
var headers = [Object.keys(json.Products[0])];
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1,1,headers.length,headers[0].length).setValues(headers);
for(var i = 0; i < json.Products.length; i++){
var final = Object.values(json.Products[i]);
getFinal.push(final);
}
sheet.getRange(2,1,getFinal.length,getFinal[0].length).setValues(getFinal);
}
Sample Result:

Data Studio Connector getData() not running

I can't seem to get the getData() function to run on this connector I'm building. Data studio displays my Schema properly, however when I go to 'explore' the data, an error is thrown. Looking in the project executions, the 'getData' function never runs at all.
Data Studio has encountered a system error.
Sorry, we encountered an error and were unable to complete your request.
There's no debug errors shown, and I'm not sure how to continue debugging this.
Here is my code...
var cc = DataStudioApp.createCommunityConnector();
function isAdminUser(){
return true
}
function responseToRows(requestedFields, response){
return response.map(function(item) {
var row = [];
requestedFields.asArray().forEach(function(field){
var id = field.getId()
row.push(item[id])
});
console.log(row);
return { values: row };
});
}
function getAuthType() {
var response = { type: 'NONE' };
return response;
}
function getConfig(){
var json = UrlFetchApp.fetch("<api-url>");
var data = JSON.parse(json);
var config = cc.getConfig();
var tables = data.TableNames
var configElement = config
.newSelectSingle()
.setId('tables')
.setName("Choose your data source")
.setHelpText('Choose your data source');
for(i=0;i<tables.length;i++){
configElement
.addOption(config.newOptionBuilder().setLabel(tables[i]).setValue(tables[i]))
}
return config.build();
}
function getSchema(request){
var fields = cc.getFields();
var types = cc.FieldType;
var table = request.configParams.tables;
var data = UrlFetchApp.fetch("<api-url>"+"?name="+table);
var itemArray = JSON.parse(data);
var singleRow = itemArray["Items"][0];
var keys = Object.keys(singleRow)
for(i=0;i<keys.length;i++){
var nestedKeys = Object.keys(singleRow[keys[i]])
var propName = keys[i];
var dataType = nestedKeys[0]
if(dataType == "S"){
fields.newDimension()
.setId(propName)
.setName(propName)
.setType(types.TEXT)
}else if (dataType == "N"){
fields.newMetric()
.setId(propName)
.setName(propName)
.setType(types.NUMBER)
}
}
console.log(fields.build());
console.log('get schema')
return { schema: fields.build() };
}
function getData(request){
var fields = cc.getFields();
console.log(fields);
console.log('getdata running');
// TODO: Create Schema for requested field
var table = request.configParams.tables;
var requestedFieldIds = request.fields.map(function(field) {
return field.name
});
var requestedFields = fields.forIds(requestedFieldIds);
// TODO: Fetch and Parse data from API
var response = UrlFetchApp.fetch("<api-url>"+"?name="+table);
var parsedResponse = JSON.parse(response)
// TODO: Transform parsed data and filter for requested fields
var rows = responseToRows(requestedFields, parsedResponse)
return {
schema: requestedFields.build(),
rows: rows
}
}
To see debug traces, you could simply log it with console.log() and take a look at your logs in the Google Apps Scripts dashboard :
https://script.google.com/home/executions
I don't know if this is related to your problem, but in my case I was trying to use URL Parameters and getData(request) wouldn't run no matter what values I input - it ended up being that I had to create a production deployment and Publish > Deploy from Manifest and then create an actual published version (not just FROM HEAD).

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