Convert JSON response to Google Sheet ( Google Apps Script) - javascript

I have been trying to figure out to insert the JSON response into google Sheet in Google Apps Script with below code but for some reason I am getting error while trying to run.
please see screenshot and below code.
function myFunction() {
var key_67 = 'YYYYYYYYYYYYYYYYYY';
var ss_67 = SpreadsheetApp.openById(key_67);
var sheet_67 = ss_67.getActiveSheet();
sheet_67.getRange('A1:AZ10000').clearContent();
var url = 'https://creator.zoho.com/api/json/arfater/view/Leads_Report?authtoken=XXXXXXXXXXXXXXXXXXXX&scope=creatorapi&zc_ownername=ipekuet';
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
var stats=[]; //create empty array to hold data points
//The following lines push the parsed json into empty stats array
stats.push(data.Yearly_Sales); //temp
stats.push(data.Email); //dewPoint
stats.push(data.Phone); //visibility
//append the stats array to the active sheet
sheet_67.appendRow(stats)
}

So your JSON response based on postman app is
var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","P‌otentially":50,"Stat‌e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]};
When I use that response as is:
function JsonResponse(){
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","P‌​otentially":50,"Stat‌​e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]} '
var data = JSON.parse(json);
Logger.log(data);
}
I get the same error as you:
SyntaxError: Unexpected token: v
Which leads me to believe your response from API has this term var zohoipekuetview65 (Not really sure as to why? a bug perhaps)
The below code splits the response string to give you the JSON response only
function trialParse(){
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","P‌​otentially":50,"Stat‌​e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]} '
Logger.log(JsonResponse(json))
}
function JsonResponse(response){
Logger.log(response)
var json = response.split("=")[1]
var data = JSON.parse(json);
Logger.log(data);
return data
}
Just call the above function in your code using var data = JsonResponse(json)
Final Note: As mentioned by Jordan Rhea you can use Logger.log(json) to output the response to your logs. To view your logs goto Views>Logs, it will show you the response you receive from Api.

Related

Fetch data via GS - response code 200 but data always "undefined"

I try to fetch the data given by https://api.llama.fi/charts/Ethereum
It looks like
[{"date":"1546560000","totalLiquidityUSD":273845651.27077854},{"date":"1546646400","totalLiquidityUSD":288674544.41292274},{"date":"1546732800","totalLiquidityUSD":297321259.6930144},{"date":"1546819200","totalLiquidityUSD":286168221.103729},{"date":"1546905600","totalLiquidityUSD":285073686.76345384}, ...
when I open it in chrome.
In python with urllib.request.urlopen() it works fine.
Here in Google Sheets I try
function myFunction() {
var data = UrlFetchApp.fetch("https://api.llama.fi/charts/Ethereum").getResponseCode()
var data2 = UrlFetchApp.fetch("https://api.llama.fi/charts/Ethereum").getContentText()
console.log(UrlFetchApp.fetch("https://api.llama.fi/charts/Ethereum").getContentText())
}
Here data = 200, but data2 = undefined. I think it is a newbie question, but I am unfamiliar with JS or GS.
Thanks for your help!
Best,
Dominik
You can access the data as JSON object by parsing the ContentText as JSON, then you can iterate the data with a for or use it in any other way you need.
function myFunction() {
var response = UrlFetchApp.fetch("https://api.llama.fi/charts/Ethereum").getContentText()
var data = JSON.parse(response);
for(const d of data) {
console.log("DATE: " + d.date)
console.log("LIQUIDITY: " + d.totalLiquidityUSD)
}
}

GoogleJsonResponseException: API call to directory.users.photos.update failed with error: Invalid Input: photoData When setting user profile picture

I'm trying to create a google app script attached to a spreadsheet that can set a google user's profile picture. According to the documentation, this should work:
var response = UrlFetchApp.fetch(url);
var photoBlob = response.getBlob();
var data = Utilities.base64EncodeWebSafe(photoBlob.getBytes());
AdminDirectory.Users.Photos.update({photoData: data}, this.email);
However this causes an exception:
GoogleJsonResponseException: API call to directory.users.photos.update failed with error: Invalid Input: photoData
The user running this script has permission to edit the profile picture
There must be a problem with your URL, the following works for me:
function myFunction() {
var url = "https://www.telegraph.co.uk/content/dam/Pets/spark/royal-canin/tabby-kitten-small.jpg"
var response = UrlFetchApp.fetch(url);
var photoBlob = response.getBlob();
var data = Utilities.base64EncodeWebSafe(photoBlob.getBytes());
var email = Session.getEffectiveUser().getEmail()
AdminDirectory.Users.Photos.update({photoData: data}, /*this.*/email);
}
Alternatively, you can also use an image from your Drive as following:
function myFunction() {
var url = "https://www.telegraph.co.uk/content/dam/Pets/spark/royal-canin/tabby-kitten-small.jpg"
var response = DriveApp.getFileById("1f8EFG6G5zNd6by_fNEecSh2D1My_p-_p")
var photoBlob = response.getBlob();
var data = Utilities.base64EncodeWebSafe(photoBlob.getBytes());
var email = Session.getEffectiveUser().getEmail()
AdminDirectory.Users.Photos.update({photoData: data}, /*this.*/email);
}

How to parse large nested json objects?

PasteBin JSON
I would like to get this as Object it says jsonlint is valid but parsing is not anyone help would appreciate
"Data":[{...},{...},] // structure build like this
when i try
JSON.parse(jsonparamter) <-- Uncaught SyntaxError: Unexpected token A in JSON at position 71
at JSON.parse (<anonymous>)
at <anonymous>:1:6
There are multiple levels of JSON encoded data so you will have to create a loop to decode the elements deeper in the JSON nest. Use the below code to see an example of accessing Data.Adress.Value in this dictionary
// set up urls and headers for making HTTP req
corsurl = 'https://cors-anywhere.herokuapp.com/'
jsonurl = 'https://pastebin.com/raw/vuecweML'
headerNames = ['Content-Type','Accept']
headerValues = [ 'application/json', 'application/json']
// Modular get request function that I use
function getRequest (baseRestURL, APIPath, headerNames, headerValues, callback) {
var completeRestURL = baseRestURL + APIPath
console.log('REST API URL: ' + completeRestURL)
var method = 'GET'
var url = completeRestURL
var async = true
var request2 = new XMLHttpRequest()
request2.onload = function () {
console.log('ONLOAD')
var status = request2.status // HTTP response status, e.g., 200 for "200 OK"
console.log(status)
console.log(request2.responseText)
var response = request2.responseText
return callback(response)
}
request2.open(method, url, async)
for (var i in headerNames) {
request2.setRequestHeader(headerNames[i], headerValues[i])
}
request2.send(null)
}
// Our code of interest
getRequest(corsurl, jsonurl, headerNames, headerValues, response => {
parsed = JSON.parse(response).Data //parse our data the first time, and get the data attribute from dictionary
objects = JSON.parse(parsed) // parse a second time ( as data is JSON encoded twice )
selection = JSON.parse(objects[0].Address)[0].Value // parse a third time and select an attribute
document.getElementById('result').innerHTML = selection // Add it to our html to display
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id='result'> Loading </div>

Pass JSON from SQL Server to D3 Javascript

I'm building an ASP.NET using C#, Visual Studio, SQL Server, D3.JS.
I have values in a SQL Server that I'm getting from the database and the results are:
[
{"AMOUNT":1.000000000000000e+002},{"AMOUNT":1.000000000000000e+003},
{"AMOUNT":1.000000000000000e+004},{"AMOUNT":5.000000000000000e+003}, {"AMOUNT":2.000000000000000e+003},{"AMOUNT":1.000000000000000e+003},
{"AMOUNT":5.000000000000000e+003},{"AMOUNT":3.000000000000000e+003},{"AMOUNT":8.000000000000000e+003},{"AMOUNT":1.200000000000000e+004},
{"AMOUNT":5.000000000000000e+003},{"AMOUNT":1.300000000000000e+004},
{"AMOUNT":1.500000000000000e+004}
]
Okay so my Json output is correct, below is code I'm using to get the json output above:
public string jsonString = "";
public string JasonGet()
{
var queryWithForJson = "SELECT AMOUNT FROM PeopleTable WHERE Bal = 'Acc' FOR JSON AUTO";
var conn = new SqlConnection(#"MyConnectSource!");
var cmd = new SqlCommand(queryWithForJson, conn);
conn.Open();
var jsonResult = new StringBuilder();
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
Label1.Text = jsonResult.ToString();
// jsonString = (new JavaScriptSerializer()).Serialize(jsonResult);
return (new JavaScriptSerializer()).Serialize(jsonResult);
}
And this works fine above I believe since I am putting the results on a label1.Text from a jsonString to see it for myself but the last return line is where I'm part confused because now I wish to pass the JSON result to my D3.JS. Let me show what I'm doing in D3...
<script>
d3.json('<%= JasonGet() %>').then(function (data) {
console.log("Json string: " + data);
});
</script>
Okay so I believe in my C# function that I have the correct results but I think the error is when I'm passing the values to my Javascript. Below is the error code I'm getting:
Uncaught SyntaxError: Unexpected end of JSON input
and
Failed to load resource: the server responded with a status of 400 (Bad Request)
I appreciate any suggestions, sorry if it's not explained properly but to sum it up, we are getting json values from the database from a C# function and then want to pass it into Javascript.

UrlFetch put method using Google Apps Script

Have tried many options to update a product in ECWID using Google Apps Script UrlFetchApp.fetch() put method but not succeeded. Following are the different ways that I've written the code and tested, but am getting different type of errors.
I guess, am missing some small thing, which am not able to figure it out. Please help me to fix this issue.
API: ECWID Products API (http://kb.ecwid.com/w/page/25285101/Product%20API#RESTAPIMethodupdateaproduct)
Method: PUT (to update the product details)
Sample Code 1:-
function updateProducts(){
var products_authkey = "xxxxxxxx";
try{
var url ="https://app.ecwid.com/api/v1/xxxxx/product?id=xxxxxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var options ={method:"put",ContentType:"application/json",payload:payload};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
}catch(e){
Browser.msgBox(e);
}
}
Error:-
"{ "error": "OTHER", "errorMessage": "Error parsing JSON: A JSONObject text must begin with '{' at character 0" }"
Version 2:-
Tried converting the object to json stringify, but the same error.
function updateProducts_version2(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product?id=xxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var payload_json = Utilities.jsonStringify(payload);
var options ={method:"put",ContentType:"application/json",payload:payload_json,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
Error:-
"{ "error": "OTHER", "errorMessage": "Error parsing JSON: A JSONObject text must begin with '{' at character 0" }"
Version 3:- (Tried passing secure_auth_key using Authorization in headers)
function updateProducts_version3(){
try{
var url ="https://app.ecwid.com/api/v1/xxxxx/product?id=xxxxx";
var payload = {price:62755};
var headers = {Authorization: 'xxxxxxx'};
var options = {headers:headers,method:"put",ContentType:"application/json",payload:payload};
var options ={method:"put",ContentType:"application/json",payload:payload,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
Error:-
{ "error": "OTHER", "errorMessage": "API key not found in request parameters" }
Also to note that, I've tried using DevHttpClient chrome plugin, it's updating properly.
Which means that there's some problem the way we're using UrlFetch. Please help me in fixing this issue...
Thanks in advance...
Credentials are needed to test this, so that's up to you. You probably need to both stringify & encode the payload. You also had incorrect capitalization on contentType, which you could check with UrlFetchApp.getRequest().
function updateProducts_version2a(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product?id=xxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var payload_json = encodeURIComponent(JSON.stringify(payload));
var options ={method:"put",contentType:"application/json",payload:payload_json,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
This next version seemed to work - by suppressing the price change and using a store's ID, it mimicked a product 'get', according to the docs you referenced. This time, the error message might be indicating some level of success: "This Ecwid account doesn't have access to Ecwid API. Please, consider upgrading it."
You'll notice that the URL has been separated out, with the basic header info of product ID and auth key together.
function updateProducts_version4(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product";
var payload = encodeURIComponent(JSON.stringify({
price:62755
}));
var headers = {id:'xxxx',
secure_auth_key: 'xxxxxxx'
};
var options = {
headers:headers,
method:"put",
contentType:"application/json",
muteHttpExceptions:true,
payload:payload
};
var request = UrlFetchApp.getRequest(url, options); // Debug: check what would be fetched
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var respHeaders = result.getHeaders(); ///
debugger;
}catch(e){
Logger.log(e);
//Browser.msgBox(e);
}
}
Without your creds, that's as far as I can take it... tell us how that works for you.

Categories