Search code examples
javascripthtmljsonbinance

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


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()][2] or [.split()][3] + [.join()][4] 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?


Solution

  • 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()