How can I ONLY grab the price value of selected crypto currency

Viewed 136

GOAL: ONLY Grab Price Value of Selected Crypto Currency! Using the Binance Public API

Problem: Returns a whole JSON string rather than just the selected currency's price.

Code:

  var burl = 'https://api.binance.com/api/v3/ticker/price?symbol='
  var symbol = 'BTCUSDT'
  var url = burl + symbol
  var ourRequest = new XMLHttpRequest()

  ourRequest.open('GET', url, true)
  ourRequest.onload = function() {
    console.log(ourRequest.responseText)
  }
  ourRequest.send()

Now do be fair I do know I can use .replace() or .split() + .join() to only get the price however I do believe there's an easier way than going thru with that method.

var burl = 'https://api.binance.com/api/v3/ticker/price?symbol='
var symbol = 'BTCUSDT'
var url = burl + symbol
var ourRequest = new XMLHttpRequest()

ourRequest.open('GET', url, true)
ourRequest.onload = function() {
  var str = ourRequest.responseText
  str = str.split('{"symbol":"BTCUSDT","price":"').join('')
  str = str.split('"}').join('')
  document.body.innerHTML = str
}
ourRequest.send()

My question is this, How can I ONLY grab the price value of selected crypto currency as text?

2 Answers

I think you can do like this

  var burl = 'https://api.binance.com/api/v3/ticker/price?symbol='
    var symbol = 'BTCUSDT'
    var url = burl + symbol
    var ourRequest = new XMLHttpRequest()
    
    ourRequest.open('GET', url, true)
    ourRequest.onload = function() {
      var str = ourRequest.responseText
      var strobj = JSON.parse(str)
     document.body.innerHTML = strobj.price
    
    }
    ourRequest.send()

Same as @EtsukoSusui but using fetch

const burl = 'https://api.binance.com/api/v3/ticker/price?symbol='
const symbol = 'BTCUSDT'
const url = burl + symbol
const res = await fetch(url)
const { price } = await res.json()
document.body.innerHTML = price
Related