Home > Back-end >  get value from API Json
get value from API Json

Time:11-01

I have this API https://api.kraken.com/0/public/Ticker?pair=BTCUSD, I want to get value from it but not working this is return of API ":

{"error":[],"result":{"XXBTZUSD":{"a":["62121.90000","16","16.000"],"b":["62121.80000","1","1.000"],"c":["62121.80000","0.00341000"],"v":["1185.98605494","2092.23776385"],"p":["60941.29739","60856.65178"],"t":[12407,29300],"l":["59449.10000","59449.10000"],"h":["62414.20000","62414.20000"],"o":"61380.10000"}}}

NOTE: The place 'XXBTZUSD' is change dynamic if I change symbol:

This is my code:

function coin() {

    var url = 'https://api.kraken.com/0/public/Ticker?pair=BTCUSD';

    var apiRequest = UrlFetchApp.fetch(url);
    var jsonResponce = JSON.parse(apiRequest);
    // Cutt array    
    var lastArray = jsonResponce.result;
    Logger.log(lastArray)

    // Get Header name of array
    for (var key in lastArray) {
    key}
    Logger.log(key)

    //var link = 
    var price = lastArray.key;  //.map(obj => [obj[0]]);
    Logger.log(price)

    //var fine = price[0];
    //Logger.log(fine)

   }

This is the return of code:

1:28:44 AM  Notice  Execution started
10:46:02 AM Info    {XXBTZUSD={c=[62183.70000, 0.00010000], b=[62182.10000, 1, 1.000], p= 
[60982.43139, 60883.39482], a=[62182.20000, 5, 5.000], l=[59449.10000, 59449.10000], 
o=61380.10000, h=[62414.20000, 62414.20000], v=[1230.40207896, 2118.15736081], t=[12840.0, 
29425.0]}}
10:46:02 AM Info    XXBTZUSD

1:46:02 AM Info null 1:28:45 AM Notice Execution completed

I want to in XXBTZUSD array get 'a' then from that '["62121.90000","16","16.000"]' find first number 62121.90000.

CodePudding user response:

You want unknown key's a entry:

function coin(pair) {

  const url = `https://api.kraken.com/0/public/Ticker?pair=${pair}`;

  fetch(url)
  .then(response => response.json())
  .then(data => {
    const key = Object.keys(data.result)[0]
    const a = data.result[key]["a"]
    console.log(key,a[0])
  })
}
coin('BTCUSD')
coin('BTCEUR')
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Using your fetch

var apiRequest = UrlFetchApp.fetch(url);
var data = JSON.parse(apiRequest);
const key = Object.keys(data.result)[0]
const a = data.result[key]["a"]
console.log(key,a[0])
  • Related