Ilan
Ilan

Reputation: 489

Fetch content from an API though JSON gives wrong data

I'm trying to fetch a number from this API:

https://api.bithumb.com/public/ticker/btc

I'm trying to get the sell_price.

My fetch function works ok, because I was able to get the data from another API very well, it was well organized in arrays.

I have this function :

var price_USD = document.getElementById('price-btc-usd-humb');
var USDPrice = data.data.sell_price;
price_USD.innerHTML = USDPrice;

or the same with

var USDPrice = data.data.sell_price[0];

both only give me the first figure of the whole number in both case.

Do you know what can be my mistake ?

Upvotes: 0

Views: 860

Answers (2)

Simon Prickett
Simon Prickett

Reputation: 4158

Issue is with:

var USDPrice = data.data.sell_price[0];

because the API returns:

{ status: "0000", data: { opening_price: "21308000", closing_price: "21140000", min_price: "20132000", max_price: "21970000", average_price: "21168606.8824", units_traded: "32077.49761093", volume_1day: "32077.49761093", volume_7day: "262188.14880950", buy_price: "21133000", sell_price: "21147000", date: "1513812135042" } }

So your code gets the 0th character of the sell_price string. Try:

var USDPrice = data.data.sell_price;

Upvotes: 0

acdcjunior
acdcjunior

Reputation: 135812

Check the following snippet. It gets the sell_price using fetch():

fetch('https://api.bithumb.com/public/ticker/btc')
  .then(function(response) {
    return response.json();
  })
  .then(function(json) {
    console.log(json);
    var price_USD = document.getElementById('price-btc-usd-humb');
    // notice USDPrice here is a string
    var USDPrice = json.data.sell_price;
    price_USD.innerHTML = USDPrice;
        
    // you can convert it to int
    var USDPriceNumber = parseInt(USDPrice);
    console.log(USDPriceNumber);
  })
  .catch(function(error) {
    console.log(error);
  });
Price: <span id="price-btc-usd-humb"></span>.

Upvotes: 2

Related Questions