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)
}
}
Related
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>
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","Potentially":50,"State":"NY","ZipCode":"10036","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","Potentially":50,"State":"NY","ZipCode":"10036","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","Potentially":50,"State":"NY","ZipCode":"10036","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.
I missed a lot of time that to resolve this problem but unlucky. I know how to render d3 tree with external file, but how to do that with generated object. I'm getting Json object thru this code:
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');
and have added json to d3.json
treeJSON = d3.json(json, function (error, treeData) {
so whole part of code looks like:
function load() {
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');
// Get JSON data
treeJSON = d3.json(json, function (error, treeData) {
the most interesting part is that console log self defined such as right string:
[{"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]}]
but I'm still getting an error:
GET http://localhost:63342/testMerg/%7B%22text%22:%22Alas%22,%22icon%22:%22…SH%22%7D]%7D,%7B%22text%22:%22CDISC%22%7D,%7B%22text%22:%22BRIDG%22%7D]%7D 404 (Not Found)
I've tried to use string method from some example which I found somewhere here:
.then(function (data) {
var json = JSON.stringify(data);
// Get JSON data
treeData = JSON.parse( data );
but got an error
Uncaught SyntaxError: Unexpected token o
so I give up... could anybody help me?
The problem arises because data is an Object and your trying to parse the object. But JSON.parse function expects a string as the parameter.
You can either directly assign treeData = data. (No need for parsing).
Or else you should try stringifying the object and then parse the stringified json.
var json = JSON.stringify(data);
treeData = JSON.parse(json);
var data = {"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]};
//treeData = data;
json = JSON.stringify(data);
console.log(JSON.parse(json));
A site that I'm using contains a JavaScript file, inside the file it contains a code with JSON and goes like this:
$.getJSON(API_URL + getSubdomain() + "/values");
The data file contains the code:
{"has_clicked_all":false,"has_clicked_already":false,"buttons":
[{"id":3922,"name":"button3992","has_clicked":false},
{"id":4613,"name":"button4613","has_clicked":false},
{"id":4339,"name":"button4339","has_clicked":false},
{"id":4340,"name":"button4340","has_clicked":false},
{"id":4341,"name":"button4341","has_clicked":false},
{"id":4622,"name":"button4622","has_clicked":false},
{"id":4623,"name":"button4623","has_clicked":false},
{"id":4828,"name":"button4828","has_clicked":false},
{"id":4829,"name":"button4829","has_clicked":false},
{"id":4861,"name":"button4861","has_clicked":false}]}
What I'm wanting to do is change all the value's to true without clicking on all of the buttons. I've tried doing a lot of research and spent 4 hours figuring out how I could do this and me being very new to all this just leaves me stuck...
I just need someone to give me a hand it would be greatly appreciated! Thankyou
Parse the json , modify the data , then re-encode to json
javascript:
var data = JSON.parse(json);
for(i = 0; i < data.buttons.length; i++){
data.buttons[i].has_clicked = true;
}
data.has_clicked_all = true;
data = JSON.stringify(data);
console.log(data);
demo
jQuery :
(function() {
$.getJSON(API_URL + getSubdomain() + "/values", function(data) {
data.has_clicked_all = true;
$.each( data.buttons, function( i, item) {
data.buttons[i].has_clicked = true;
});
data = JSON.stringify(data);
alert(data);
});
})();
So I have an application in JavaScript that takes a users photo and then sends it off to a face recognition API and it returns a JSON value, Then I have that converted to a string. But I only two of the items that are returned to me are important.I want to pull out those two (uid and confidence) and set them as variables; which I'm not entirely sure how to do. Here's an example of what is returned:
{"photos":[{"url":"http://api.skybiometry.com/fc/images/get?id=bmN2X3hybD0wMTk5c29ub3I0MXE0bjN…RyMTQzJmVxPTE1ODkmY3ZxPTY5MjcxMzEyMTI3cTImZ3Z6cmZnbnpjPTIwMTMwNDE0MTgxNjI5","pid":"F#0deeecd9274c7d8357343ed57e6aaf6c_69271312127d2","width":380,"height":300,"tags":[{"tid":"TEMP_F#0deeecd9274c7d8357343ed500c20089_69271312127d2_51.05_45.67_0_1","recognizable":true,"threshold":20,"uids":[{"uid":"sam#sam","confidence":100}],"confirmed":false,"manual":false,"width":20,"height":25.33,"center":{"x":51.05,"y":45.67},"eye_left":{"x":56.32,"y":39.67},"eye_right":{"x":46.32,"y":40},"mouth_center":{"x":48.68,"y":55.67},"nose":{"x":50.79,"y":47},"yaw":0,"roll":1,"pitch":0,"attributes":{"face":{"value":"true","confidence":60}}}]}],"status":"success","usage":{"used":5,"remaining":95,"limit":100,"reset_time_text":"Sun, 14 April 2013 18:20:53 +0000","reset_time":1365963653}}
Here is the code I'm currently using right now to return the entire string:
.done(function (result) {
alert("Received response..");
var resultObject = JSON.stringify(result);
alert(resultObject);
});
Any help is greatly appreciated!
.done(function (result) {
if(result != null) {
var uids = result.photos[0].tags[0].uids[0];
var uid = uids.uid;
var confidence = uids.confidence;
} });