user9081620
user9081620

Reputation:

NodeJS Undefined JSON object

just posting a question as I have seen some other similar questions on here but none with a method that seemingly works for me.

I'm new to NodeJS and playing around with requesting data from an API. For my test here im just trying to pull ticker prices based on the input of a prompt from the user.

This works fine, however the object

This is the code I am using to try and make this work:

 prompt.start();
 prompt.get(['coin'], function (err, result) {

   request({url: `https://min-api.cryptocompare.com/data/price?fsym=${result.coin}&tsyms=BTC,USD`, json:true}, function(err, res, json) {
     if (err) {
       throw err;
     }
     console.log(json);
     var json = JSON.stringify(json);
     var string2 = JSON.parse(json);
     console.log(string2.btc_price);
     console.log(json);
   });
   console.log('Retrieving: ' + result.coin);
 });

The API request works, however it returns JSON that looks like this with my 3 console logs:

    { set_attributes: { btc_price: 1, usd_price: 15839.35 } }
    undefined 
    {"set_attributes":{"btc_price":1,"usd_price":15839.35}}  --  (Stringify'd response)

I want to be able to extract the btc_price & usd_price as variables, ive tried a few different methods and can't figure out where exactly im going wrong. Any help would be greatly appreciated!

Cheers,

J

Upvotes: 0

Views: 388

Answers (2)

boulaffasamine
boulaffasamine

Reputation: 21

axios has more stars on Github, more followers on Github and more forks.

Features

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

Using async / await

  // Make a request for a user with a given ID
  var preload = null;
  async function getPrice(symbol) {
        preload = await axios.get('https://min-api.cryptocompare.com/data/price?fsym=${symbol}&tsyms=BTC,USD')
  .then(function (response) {
        preload = response.data;
  })
  .catch(function (error) {
        console.log(error);
  });
  return `preload.BTC = ${preload.BTC}; preload.BTC = ${preload.BTC}`;
  };
  getPrice('ETH');
  // return preload.BTC = 0.04689; preload.USD = 742.85

Upvotes: 0

Adam McCormick
Adam McCormick

Reputation: 1670

When you attempt to extract the btc_price attribute, it's actually nested so your second console should read console.log(string2.set_attributes.btc_price);

Upvotes: 2

Related Questions