I am a javascript noob. I have the following function below but for some reason I cannot access the JSON object with the findTokenAddress variable.
Here is my sample code below. An example of a valid findTokenAddress could be: 0x0327112423f3a68efdf1fcf402f6c5cb9f7c33fd
.
Which should return:
{"symbol":"BTC++","name":"PieDAO BTC++","decimals":18,"address":"0x0327112423f3a68efdf1fcf402f6c5cb9f7c33fd","logoURI":"https://tokens.1inch.io/0x0327112423f3a68efdf1fcf402f6c5cb9f7c33fd.png","tags":["tokens"]}
But for whatever reason this does not work. Could someone tell me what I'm missing here?
function getTokenDetails(findTokenAddress) {
var url = `https://api.1inch.io/v4.0/1/tokens`;
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("accept", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const jsonResponse = JSON.parse(xhr.responseText).tokens;
if (findTokenAddress in jsonResponse) {
console.log(jsonResponse[findTokenAddress]);
const tokenDetails = jsonResponse[findTokenAddress];
console.log(tokenDetails);
} else {
console.log(findTokenAddress in jsonResponse);
alert("Could not find token in json?");
}
} else {
alert("Error!");
}
}
};
xhr.send();
}
getTokenDetails('0x0327112423f3a68efdf1fcf402f6c5cb9f7c33fd');
Here's what the JSON looks like from the url:
{"tokens":{"0x0327112423f3a68efdf1fcf402f6c5cb9f7c33fd":{"symbol":"BTC++","name":"PieDAO BTC++","decimals":18,"address":"0x0327112423f3a68efdf1fcf402f6c5cb9f7c33fd","logoURI":"https://tokens.1inch.io/0x0327112423f3a68efdf1fcf402f6c5cb9f7c33fd.png","tags":["tokens"]},"0x04fa0d235c4abf4bcf4787af4cf447de572ef828":{"symbol":"UMA","name":"UMA Voting Token v1","decimals":18,"address":"0x04fa0d235c4abf4bcf4787af4cf447de572ef828","logoURI":"https://tokens.1inch.io/0x04fa0d235c4abf4bcf4787af4cf447de572ef828.png","tags":["tokens"]},"0x08d967bb0134f2d07f7cfb6e246680c53927dd30":{"symbol":"MATH","name":"MATH Token","address":"0x08d967bb0134f2d07f7cfb6e246680c53927dd30","decimals":18,"logoURI":"https://tokens.1inch.io/0x08d967bb0134f2d07f7cfb6e246680c53927dd30.png","tags":["tokens"]},"0x0a913bead80f321e7ac35285ee10d9d922659cb7":{"symbol":"DOS","name":"DOS Network Token","decimals":18,"address":"0x0a913bead80f321e7ac35285ee10d9d922659cb7","logoURI":"https://tokens.1inch.io/0x0a913bead80f321e7ac35285ee10d9d922659cb7.png","tags":["tokens"]},"0x0ae055097c6d159879521c384f1d2123d1f195e6":{"symbol":"STAKE","name":"STAKE","address":"0x0ae055097c6d159879521c384f1d2123d1f195e6","decimals":18,"logoURI":"https://tokens.1inch.io/0x0ae055097c6d159879521c384f1d2123d1f195e6.png","eip2612":true,"tags":["tokens"]},"0x88df592f8eb5d7bd38bfef7deb0fbc02cf3778a0":{"symbol":"TRB","name":"Tellor Tributes","address":"0x88df592f8eb5d7bd38bfef7deb0fbc02cf3778a0","decimals":18,"logoURI":"https://tokens.1inch.io/0x0ba45a8b5d5575935b8158a88c631e9f9c95a2e5.png","tags":["tokens"]}...