Search code examples
javascriptnode.jsjsoncoinmarketcap

Can't fetch data inside JSON what I want and what's the difference between this two?


I've looked at many similar issues but couldn't find it. My purpose is to get the coin name and value. There are 2 endpoints in the Coinmarketcap API. First one that in the comment line gives me the output I want and it works , but I need the second one but not works. Both have the similar JSON structure.

First endpoint's output like this and JSON https://pastebin.com/xSS85Sbd

name: 'Bitcoin', price: 43973.31953486187,
name: 'Ethereum', price: 3097.8947589293316

Some errors I got on the 2nd and JSON https://pastebin.com/0sDXXwxm

coin.data.map is not a function
Cannot read properties of undefined (reading 'name')

I tried below and more and several console.log varieties with and without map but could not be succcessful.

coin.map(a => ({ name: a.name, price: a.quote.USD.price}))
coin.data.map(a => ({ name: a.name, price: a.quote.USD.price}))
async function getCoin(){
  try {
    //const response = await axios.get('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?limit=2', {
    const response = await axios.get('https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest?symbol=BTC,ETH', {
      headers: {
        'X-CMC_PRO_API_KEY': 'key',
      },
    });

    const coin = response.data;
    const result = coin.data.map(a => ({ name: a.name } ))

    console.log(result);

    //return coin;

    } catch(ex) {
    console.log(ex);
    throw ex;
  }
}
getCoin()

I really wonder where I am wrong. Many thanks.


Solution

  • It can not run because they have different structure.

    In 1st JSON data is array so you can use map

    {
    ...
    "data":[{"id":1,"...
    ...
    }
    

    In the 2nd data is object so it will throw error coin.data.map is not a function

    {
    ...
    "data":{"BTC"...
    ...
    }
    

    Update

    You can get coin info like this

    const result = Object.keys(coin.data).map(coinName => {
      const coinInfo = coin.data[coinName][0]
      return {
        name: coinInfo.name,
        price: coinInfo.quote.USD.price
      }
    })
    console.log('result: ', result)