我怎样才能只抓取所选加密货币的价格值

问题描述

目标:仅获取所选加密货币的价格!使用 Binance Public API

问题:返回整个 JSON 字符串,而不仅仅是所选货币的价格。

代码

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

现在公平一点,我知道我可以使用 .replace().split() + .join() 来只获取价格,但我相信有比使用该方法更简单的方法

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',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()

我的问题是,我怎样才能仅以文本形式获取所选加密货币的价格值?

解决方法

我觉得你可以这样做

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

,

与@EtsukoSusui 相同,但使用 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...