JSON import - Cannot read property 'length' of undefined - json

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

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)

Google sheet to BigQuery by GAS

I am following the instruction below link with following code ( to make a app script to send data to big query from google sheet ):
function myFunction() {
var projectId = 'tcndata';
var datasetId = 'dec06';
var tableId = 'dec0601';
var fileId = '1Mb7tN3xshHt0gpsxHkt5Ifje4xAeu7N9Vn_YEQAdcoc';
var ss = SpreadsheetApp.openById(fileId);
var source = ss.getSheetByName("send");
var dataToCopy = source.getRange('A2:D5');
var values = dataToCopy.getValues();
var rowsCSV = values.join("\n");
var data = Utilities.newBlob(rowsCSV, 'application/octet-stream');
function convertValuesToRows(data) {
var rows = [];
var headers = ["Contract","Product","Dest","QTY"] ;
for (var i = 1, numColumns = data.length; i < numColumns; i++) {
var row = BigQuery.newTableDataInsertAllRequestRows();
row.json = data[i].reduce(function(obj, value, index) {
obj[headers[index]] = value;
return obj
}, {});
rows.push(row);
};
return rows;
}
function bigqueryInsertData(data, tableId) {
var insertAllRequest = BigQuery.newTableDataInsertAllRequest();
insertAllRequest.rows = convertValuesToRows(data);
var response = BigQuery.Tabledata.insertAll(insertAllRequest, projectId, datasetId, tableId);
if (response.insertErrors) {
Logger.log(response.insertErrors);
}
}
bigqueryInsertData(Utilities.parseCsv(data.getDataAsString()), tableId);
}
'''
The script also no error but the big query no record data.
Any one can help, to figure out what is reason ?
Thank you
You could see these options:
You should validate the headers’s name, as it needs to match the
column names of the table in BigQuery
You should validate converting the rowsCSV to a blob to use
getDataAsString
You should validate the name of the sheet is correct
ss.getSheetByName("send"); you can use ss.getSheets()[0];
You should validate the range has data source.getRange('A2:D5'). You
can use this format getRange(row, column, numRows, numColumns).Yo can see more documentation about getRange.
Another option is for you to load CSV data from Cloud Storage into a new BigQuery table by. You can see this example:
from google.cloud import bigquery
# Construct a BigQuery client object.
client = bigquery.Client()
# TODO(developer): Set table_id to the ID of the table to create.
# table_id = "your-project.your_dataset.your_table_name"
job_config = bigquery.LoadJobConfig(
schema=[
bigquery.SchemaField("name", "STRING"),
bigquery.SchemaField("post_abbr", "STRING"),
],
skip_leading_rows=1,
# The source format defaults to CSV, so the line below is optional.
source_format=bigquery.SourceFormat.CSV,
)
uri = "gs://cloud-samples-data/bigquery/us-states/us-states.csv"
load_job = client.load_table_from_uri(
uri, table_id, job_config=job_config
) # Make an API request.
load_job.result() # Waits for the job to complete.
destination_table = client.get_table(table_id) # Make an API request.
print("Loaded {} rows.".format(destination_table.num_rows))
You can see this documentation.

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.

Access JSON position in Node.js

I have a JSON string in this format:
[
{
"Origin":{
"FtpHost":"info",
"FtpFolder":"info",
"FtpUser":"info",
"FtpPassword":"info",
"FtpInsideFolder":"info",
"Pattern":"info"
},
"Destination":{
"FtpHost":"info",
"FtpFolder":"info",
"FtpUser":"info",
"FtpPassword":"info",
"FtpInsideFolder":"info"
},
"CustomFolderName":"Conad",
"OperationTraverseType":"RootOnly"
}
]
To pick up the JSON I wrote this in Node.js:
var fs = require('fs');
var obj = fs.readFileSync('Operations.json', 'utf8');
I'm wondering, how I can access for example : "Destination" fields?
You must parse this to JSON. because fs.readFile returns string
var fs = require('fs');
var obj = fs.readFileSync('Operations.json', 'utf8');
obj = JSON.parse(obj)
var Destination = obj[0].Destination
// or
var Destination = obj[0]["Destination"]
Edit (as said Diego)
You can also directly require json file
var obj = require('somejsonfile.json');
var Destination = obj[0]. Destination
Just need to simply parse the read data. Something like this:
var fs = require('fs');
var obj = fs.readFileSync('Operations.json', 'utf8').toString();
obj = JSON.parse(obj)
console.log(obj[0].Destination)
you can do like var myjson = JSON.parse(obj) or obj = JSON.parse(fs.readFileSync('Operations.json', 'utf8')) and then access it like obj[0]["Destination"]["FIELD"] where FIELD - represents the "Destination" object field you want

Uncaught SyntaxError, Unexpected Identifier in for loop in jade

I am trying to render a jade with some dynamic content. I am reading from a json in jade.
My json looks like this
{ data1: 'data1',
data2: 'data2',
data3:
[ { name: 'ABC',
address: 'India'
},
{ name: 'DEF',
address: 'Australia'
}]}
I am trying to render a jade and use the data from above json
my jade looks like
var data1 = #{data1};
var data2 = #{data2};
var size = #{data3.length};
for data in #{data3}
var name = data.name;
var address = data.address;
I am able to correctly extract data in the first 3 lines mentioned above. But when I try to fetch data from within a loop, I get "Uncaught SyntaXError, Unexpected Identifier" error while debugging.
If i put a line outisde the for loop, it works fine. Ex
var name = #{data3[0].name};
is rendered properly. But i need to iterate over a loop and fetch data over there. Can somebody help.
Thanks
Updating with more information
1. I have node server running where I create a json -
var json_string = "{"data1":"data1","data2":"data2","data3":[{"name":"ABC","address":"India"},{"name":"DEF","address":"Australia"}]};";
var json_data = JSON.parse(json_string);
console.log(json_data);
res.render('sample_example', json_data);
In my sample_example.jade I have the following snippet within script
var data1 = #{data1};
var data2 = #{data2};
var size = #{data3.length};
for data in #{data3}
var name = data.name;
var address = data.address;
As stated earlier, I am able to properly extract #{data1}, #{data2}, #{data3.length} to the variables . But it breaks within the for loop. In fact, I am able to extract #{data3[0].name} from outside the for loop. But within the for looop it gives the stated error.
This is how you can do it now.
In your server-side you have to JSON.stringify the array of objects.
var json_data = JSON.parse(json_string);
// Convert back to json only the property data3
json_data.data3 = JSON.stringify(json_data.data3);
res.render('simple', json_data);
Or the better is to not parse the JSON just let it go the way it is:
// var json_data = JSON.parse(json_string);
res.render('simple', {
json_data: json_string
});
And in the Jade Template (If you followed the better method):
script(type='text/javascript').
var json_data = !{json_data};
var data1 = json_data.data1;
var data2 = json_data.data2;
var data3 = json_data.data3;
var size = data3.length;
data3.forEach(function(data) {
var name = data.name;
var address = data.address;
console.log(name, address);
});
Also you need to change the loop structure. The for..in used to iterate over objects not array of objects.
This works for me;
- var cdata = {"data1":"data1","data2":"data2","data3":[{"name":"ABC","address":"India"},{"name":"DEF","address":"Australia"}]};
each data in cdata.data3
- var name = data.name;
- var address = data.address;
p Name: #{name}
p Address: #{address}
Can you share the actual jade file contents if updating the code as shown above doesn't work. Also what version of jade and express?