I have been trying to figure this out for hours. I've seen this SO question and I still cannot figure this out.
I have some Jason data that I know begins like this:
{
"0x123454843eacf5c5318e1234504251b937d12345": [
{
"poolIndex": 0,
"stakingStrategy": "masterchef",
"farmName": "sushiChef",
....
I've written the following to get at the information like "poolIndex" and "stakingStrategy":
function parseTheDataFunctionSushi(walletAddress, networkName){
// calls a funciton to pull and parse the api data
var walletAddress = "0x123454843eacf5c5318e1234504251b937d12345";
var networkName = "polygon";
var theparsedJSONdata = pullAndParseAPISushi(walletAddress, networkName)
console.log("object keys are " + Object.keys(walletAddress));
var firstCrack = theparsedJSONdata[walletAddress][0]['poolIndex']
console.log("firstCrack is " + firstCrack)
This does not work. I've written firstCrack every way I can think of
theparsedJSONdata[walletAddress].poolIndex
theparsedJSONdata[walletAddress][0].poolIndex
None of them work. So frustrating. Any help would be appreciated.
For what it's worth, `Object.keys(walletAddress) returns
object keys are 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41
Here's the other function:
function pullAndParseAPISushi (walletAddress, networkName){
console.log("walletAddress inside pullAndParseAPISushi is = " + walletAddress);
console.log("network is " + networkName);
var apiKEY = "96e0cc51-a62e-42ca-acee-910ea7d2a241"; // API key from Zapper
var url = "https://api.zapper.fi/v1/staked-balance/masterchef?addresses%5B%5D="+ walletAddress + "&network=" + networkName + "&api_key=" + apiKEY;
// assembles the API URL with the wallet addressa, network and name
console.log("url is " + URL);
var response = UrlFetchApp.fetch(url); // pulls data from the API
console.log(response)
var theparsedJSONdata = JSON.parse(response); // parses the JSON response from the API
console.log(theparsedJSONdata)
return theparsedJSONdata
}
If the data structure is indeed as you specified, then one of the attempts you tried should work. See below for a functional example.
const data = {
"0x123454843eacf5c5318e1234504251b937d12345": [
{
"poolIndex": 0,
"stakingStrategy": "masterchef",
"farmName": "sushiChef",
}
]
}
const walletAddress = "0x123454843eacf5c5318e1234504251b937d12345";
console.log(data[walletAddress][0].poolIndex);
console.log(data[walletAddress][0].stakingStrategy);
Have you tried?
theparsedJSONdata.walletAddress[0].poolIndex
don't have enough rep to make a comment but I think this might work, let me know!
Related
This question already has answers here:
Converting an object to a string
(40 answers)
Closed 4 years ago.
I am new to Firebase and I am trying to learn how to retrieve nested data from Firebase and print out on a webpage. I can print out all the data in the console but not on the webpage and I will get back [object Object] on the webpage. Can someone please kindly explain to me why is my webpage is printing out [object Object]? Is it something to do with "ref.on" or "snap =>"?
This is my function to get the data from Firebase:
function GetData()
{
var ref = firebase.database().ref('Scores');
var PrintData = document.getElementById('PrintOutData');
ref.on("value", function(snapshot)
{
snapshot.forEach(function(childSnapshot)
{
var childData = childSnapshot.val();
var id=childData.id;
console.log(childData);
ref.on('value', snap => PrintData.innerText = childData);
});
});
}
This is what in my console log:console.png
And this is what on my webpage: web.png
And this is my data on my Firebase:
What I want to get on my webpage is like this:
name:"AAA", score:100, time:"30s"
name:"AAA", score:100, time:"30s"
...
Thanks alot!
You can use:
let keys = Object.keys(childData)
keys.forEach(key => {
let value = childData[key.toString()];
console.log(value) // Use Value
})
Yikes, that looks pretty bad. Not sure why you're nesting an on("value" listener, and I also don't know where .id comes from. You're probably looking for something along these lines:
ref.on("value", function(snapshot) {
PrintData.innerText = ""; // We got a new value, so clear the existing HTML
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
PrintData.innerText += "name: " + childData.name + " score: " + childData.score + " time: " + childData.time + " ";
});
});
My knowledge of front end it is not so good, and I don't know how to send array of ids to back end which will get all data and will be open it into new page. pls help
there my function:
#has_session_params('tin')
def print_documents(request):
doc_ids = request.POST.getlist('doc_ids[]')
tin = request.session['tin']
params = dict()
template = 'documents/documents_to_print.html'
params['Docs'] = docs
params['pb'] = pb
params['is_pdf'] = request.GET.get('is_pdf', 'false')
params['host'] = request.scheme + "://" + request.META["HTTP_HOST"]
params['url'] = settings.SITE_URL + request.get_full_path()
params['doc_type'] = INVOICE_TYPE
invoice_list = list()
for doc_id in doc_ids:
response = proxy.get_invoice_by_id(invoice_id=doc_id, tin=tin)
if response.status.code != pb.ResponseStatus.OK:
response = proxy.get_invoice_draft_by_id(
invoice_draft_id=doc_id, tin=tin)
invoice_list.append(response.invoice)
params['invoices'] = invoice_list
return render(request, template, params)
I know how to get one object by id, it will be like:
def print_document(request, doc_id):
and something like that, and where url for function will be look like that:
url(r'^print_documents/(?P<doc_id>[a-z\d]{24})/$', invoices.print_documents, name='print_documents')
and new page link will be like that localhost:8000/documents/print_documents/{doc_id}
and this method I can just call like :
print
but now I want to select several documents and send doc_ids, and I know that I can to like method above but I don't want big link. And how I can send array of ids to back end correctly?
now I have something like that:
printAll.on("click", function(){
var invoicesID = [];
$('input.select-inv-check:checked').each(function() {
invoicesID.push($(this).data('docid'));
});
var url = Globals.printAll;
$.post( url, { doc_ids: invoicesID } ).done(function(result) {
console.log("result", result[0].Docs);
if(result.code == 0){
}else{
alert(result.message);
}
});
});
And I know that it doesn't correct! pls help
I've been working with the Microsoft Bot Framework to create a bot that can interface between MS Teams and AWS. I've been trying to write some JS functions but have been unsuccessful in getting them to operate how I want them to.
Here is what I am currently working on and am stuck on:
I am creating a 'ping' like functionality so a bot user can ping an instance in AWS and receive its status whether its running and has passed the system checks or not. My code is currently able to take the user request for the ping, retrieve the information from AWS, and can even print that info to the console. However, when I am trying to retrieve that information back out of the object that I set it to and print it to MS Teams, it says my variable is undefined.
Some code snippets are below:
class aws_Link {
constructor (mT, ping_1, i_state, i_status) {
this.myTag = mT;
this.ping = ping_1;
this.instance_state = i_state; // I declare this here, but should I?
this.instance_status = i_status; // I declare this here, but should I?
}
//i_state and i_status are just passed NULL when the object is initialized
//so they would be holding some value, not sure if I have to do this
api_link () {
var mainLink = API_LINK_TAKEN_OUT_FOR_OBVIOUS_REASONS;
var myTagFill = "myTag=";
var ampersand = "&";
var pingFill = "ping=";
var completeLink = String(mainLink + myTagFill + this.myTag + ampersand + pingFill + this.ping);
var finalLink = completeLink;
finalLink = finalLink.split(' ').join('');
//set up API-key authenticication
var options = {
url: finalLink,
headers: {
'x-api-key': 'AWS-PRIVATE-TOKEN'
}
};
if(this.ping == "TRUE") { // if the user wants to use /ping
var res = request(options, function(error, response, body) {
console.log("PING REQUEST"); //debug
body = JSON.parse(body);
var h_state = body['instanceState'];
var h_status = body['instanceStatus'];
this.instance_state = h_state;
this.instance_status = h_status;
console.log("STATE: " + h_state); //debug
console.log("STATUS: " + h_status); //debug
});
}
}
pingFunction () {
var tmp = "Instance State: " + this.instance_state + " Instance Status: " + this.instance_status;
return tmp;
}
}
And here is where I call the api_link() function and pingFunction():
var apiLink1 = new aws_Link("MY_TAG_VALUE", "TRUE", "NULL", "NULL");
var completeAPILink = apiLink1.api_link();
session.send('Request complete.');
session.send("PING: " + apiLink1.pingFunction());
So essentially the user enters in some info which gets passed to where I create the "new aws_Link" which then a my understanding is, creates an object called apiLink1. From there, it makes the request to AWS in my api_link() function, which retrieves the info I want. I thought I was then saving this info when I do the: this.instance_state = h_state; & this.instance_status = h_status;. So then when I call pingFunction() again on apiLink1, I thought I would be able to retrieve the information back out using this.instance_state and this.instance_status, but all it prints out is undefined. Any clarification on why my current code isn't working and any changes or improvements I can make would be greatly appreciated.
Thanks!
I found this website http://www.mess.be/inickgenwuname.php
It allows you to type in a name and it will generate a random rapper name. I wanted to have a button on my website that just generates the name for you so I decided to write some javascript that will send a request to this website and parse the response to get the random name.
Here is the node.js code I wrote.
function getRandomName() {
var http = require('http');
var data = {
realname:"something"
};
var querystring = require("querystring");
var qs = querystring.stringify(data);
var qslength = qs.length;
var options = {
hostname: "www.mess.be",
path: "/inickgenwuname.php",
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': qslength
}
};
var str = "";
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
str+=chunk;
});
res.on('end', function() {
var s = str.slice(str.indexOf("From this day forward, I will be known as... ") + "From this day forward, I will be known as... ".length,
str.indexOf("-And you"));
s = s.replace("\n", "").trim();
console.log(s);
});
});
req.write(qs);
req.end();
}
When I went to the website and pressed f12 on chrome and inspected the code, I found this little segment...
So this is what I used to formulate the request to the php. However, I only guessed through trial and error that the data that needed to be send was key-value pair object where the key is realname. My question is, how would I have known this otherwise? Is there no way to find out from the website, where the data being send with the POST is being received from?
Why by guessing? The form tells you everything that needs to be sent.
Also you could press F12 -> Network, and then send the request. After this you look at the sent requests and search for a POST request. When you click on the /inickgenwuname.php request you get more information about it. In there you can see Response Headers / Request Headers and as a last category "Form Data". There you can see all the data that is sent with this form.
I hope this is the answer you were looking for.
Stealing bandwidth without proper compensation (so called web-scraping) is quite commonly frowned upon. I couldn't find anything on that site that allows for it although I did not search thoroughly.
Why don't you roll your own? It's very simple, as can be seen in this Q&D hack:
function wu_names(input){
// some nice, fitting adjectives. Add more
var adjectives = ["annoying", "crazy", "expert", "insane", "lucky", "sardonic", "pestering"];
// some nice, fitting nouns. Add more
var nouns = ["assassin", "bastard", "conjurer", "destroyer", "ninja", "prophet", "wizard"];
var first = "";
var second = "";
var hash = 0;
var primitive_hash = function(s){
var h = 0;
for(var i = 0;i < s.length;i++){
var c = s.charCodeAt(i);
// standard hash = hash * 31 + c
h = ((h << 5) - h>>>0) + c;
}
return h;
};
first = input.split(" ")[0];
// no useful entry at all
if(first === undefined){
return null;
}
hash = primitive_hash(first);
first = adjectives[hash % adjectives.length];
second = input.split(" ")[1];
// no second entry
if(second === undefined){
return null;
}
hash = primitive_hash(second);
second = nouns[hash % nouns.length];
return first + " " + second;
}
The lists of adjectives and nouns is quite short, you might add to them, as the comments suggest.
I am currently, trying to National Library of Australia's API to find pictures on a specific search term. Trove API I have the following functions which should send a query from an input form to the api and receive images back, however I am not receiving the majority of the images. In a particular example, if is search for 'sydney' I am only receiving 3 images back when there is in fact way more. For instance, this is the json, that is returned. I know that you will not be familiar with this api, but in my code below, is there anything that you can see, that would be causing it not to return all the images? I have changed a few things around to try and find the problem as well as put a few console.log statements but it is still not being kind to me.
var availableImages = {
"nla": {
"numImages":0,
"url_pattern":"nla.gov.au",
"images":[]
},
};
var url_patterns = ["nla.gov.au"];
$(document).ready(function(){
$("form#searchTrove").submit();
$("form#searchTrove").submit(function() {
resetImageData();
//get input values
var searchTerm = $("#searchTerm").val().trim();
searchTerm = searchTerm.replace(/ /g,"%20");
var sortBy = $("#sortBy").val();
//create searh query
var url = "http://api.trove.nla.gov.au/result?key="
+ apiKey + "&l-availability=y%2Ff&encoding=json&zone=picture"
+ "&sortby=relevance&n=100&q=" + searchTerm + "&callback=?";
//print JSON object
console.log(url);
//get the JSON information we need to display the images
$.getJSON(url, function(data) {
$('#output').empty();
$.each(data.response.zone[0].records.work, processImages);
//console.log(data);
printImages();
});
});
});
function processImages(index, troveItem){
console.log("av"+ availableImages);
for(var i in availableImages){
//console.log(availableImages[i].url_pattern)
if(troveItem.identifier[0].value.indexOf(availableImages[i].url_pattern) >= 0){
console.log("Trove URL "+troveItem.identifier[0].value+" Pattern: "+availableImages[i]["url_pattern"]);
availableImages[i].numImages++;
availableImages.totalimages++;
availableImages[i]["images"].push(troveItem.identifier[0].value);
}
}
}
function printImages(){
$("#output").append("<h3>Image Search Results</h3>");
for(var i in availableImages){
if(availableImages[i]["url_pattern"]=="nla.gov.au" && availableImages[i]["numImages"]>0){
printNLAImages();
console.log(availableImages);
}
}
}
function printNLAImages(){
$("#output").append("<h3>National Library of Australia</h3><p>"
+availableImages["nla"]["numImages"]+" images found from <a href='http://"
+availableImages["nla"]["url_pattern"]+"'>"
+availableImages["nla"]["url_pattern"]+"</a></p>");
for (var i in availableImages["nla"]["images"]){
$("#output").append("<img src='"+availableImages["nla"]["images"][i]+"-v'>");
}
console.log(availableImages);
}
function resetImageData(){
availableImages.totalimages = 0;
for (var i in availableImages){
availableImages[i].numImages = 0;
availableImages[i]["images"] = [];
}
console.log(availableImages); //displaying hee
}