简体   繁体   中英

How to get the data from JSON object

I would like to know how to get a data from JSON object with JS. Here is my code.

  const currency_one = currencyOne.value;
  const currency_two = currencyTwo.value;

  const myHeaders = new Headers();
  myHeaders.append('apikey', API_KEY);

  const requestOptions = {
    method: 'GET',
    redirect: 'follow',
    headers: myHeaders,
  };

  fetch(
    `https://api.apilayer.com/exchangerates_data/convert?to=${currency_one}&from=${currency_two}&amount=${amountOne.value}`,
    requestOptions
  )
    .then((res) => res.text())
    .then((data) => console.log(data))
    .catch((err) => console.log('error', err));
};

Also, the console only shows look like below.

{
    "success": true,
    "query": {
        "from": "AED",
        "to": "USD",
        "amount": 1
    },
    "info": {
        "timestamp": 1662496624,
        "rate": 0.27225
    },
    "date": "2022-09-06",
    "result": 0.27225
}

I need only "result" part.

Thanks for your help!

If data is already an object, you can access result with:

console.log(data.result);

or if data is a string, you can do:

let parsd = JSON.parse(data);
console.log(parsd.result);

If you don't know what it is, try:

console.log(typeof data);

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