如何将来自REST API响应的数据存储在变量中?

时间:2019-06-10 04:52:09

标签: javascript rest npm

说这是回应

{
  "symbol": "LTCBTC",
  "bidPrice": "4.00000000",
  "bidQty": "431.00000000",
  "askPrice": "4.00000200",
  "askQty": "9.00000000"
}

我如何将AskPrice中的4.00000200仅存储为变量,以便以后可以进行数学运算?

另一个问题的答案未解释如何存储响应。他们介绍了如何在存储了一部分内容后将其获取。

3 个答案:

答案 0 :(得分:1)

您可以在这样的变量中获得响应。您可以在obtdata中获取重新操作的所有数据

var obtdata = { 
  "symbol": "LTCBTC",
  "bidPrice": "4.00000000",
  "bidQty": "431.00000000",
  "askPrice": "4.00000200",
  "askQty": "9.00000000"
}

var symbol = obtdata.symbol
var bidPrice =obtdata.bidPrice
var bidQty =obtdata.bidQty
var askPrice =obtdata.askPrice
var askQty =obtdata.askQty

有关更多信息,请访问此link

答案 1 :(得分:0)

您可以通过object_name.property访问对象响应对象属性

let price = response.askPrice

答案 2 :(得分:0)

JavaScript是异步的,您需要使用async / await或在接收到数据后使用回调来获取数据:

async function getData(){
    var obtdata = await binanceRest.bookTicker({symbol: 'BTCUSDT'})
    var symbol = obtdata.symbol
    var bidPrice = obtdata.bidPrice
    var bidQty = obtdata.bidQty
    var askPrice = obtdata.askPrice
    var askQty = obtdata.askQty

    console.log(askPrice);
}

使用回调函数:

 binanceRest.bookTicker({symbol: 'BTCUSDT'},(obtdata)=>{
    var symbol = obtdata.symbol
    var bidPrice = obtdata.bidPrice
    var bidQty = obtdata.bidQty
    var askPrice = obtdata.askPrice
    var askQty = obtdata.askQty

    console.log(askPrice);
})