简体   繁体   中英

json and data returned from api's

I'm new to coding and just paying around, but i have what I think is really simple problem, but just don't have the necessary vocabulary to express it properly. Here is my code, its for currency conversion.

app.get('/currency', (request, response) => {
  const from_currency = request.query.from;
  const to_currency = request.query.to;
  const amount = request.query.amount;
  const exchange = `${from_currency}_${to_currency}`

  //https://free.currencyconverterapi.com/api/v5/convert?q=USD_PHP&compact=y
  const currencyUrl = `https://free.currencyconverterapi.com/api/v5/convert?q=${from_currency}_${to_currency}&compact=y`;

  const requestOptions = {
    uri: currencyUrl,
    json: true
  };

  requestPromise(requestOptions)
    .then((data) => {
      //const responseData = getCurrentCurrencyJSON(data);
      response.json(data); //responseData
    })
    .catch((error) => {
      console.log(error.message);
      response.json({
        messages: [{
          text: 'Sorry there was an error!'
        }]
      });
    });
});

This returns, from the API, {"USD_GBP":{"val":0.73897}}, which is fine and I can return the value if i write response.json(data.USD_GBP.val); however I want to be able to vary the currencies im converting to and from, so how do I make the USD_GBP in the response.json dynamic?

thanks if anyone can help.

If the api is always going to return an object with than single attribute, you can do something like this:

res = {"USD_GBP":{"val":0.73897}};
res[Object.keys(res)[0]].val

Not the nicest, but it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM