如何使用jquery从http请求中检索特定的json数据

时间:2017-12-28 22:03:55

标签: jquery json ajax

我正在尝试使用jquery从下面列出的JSON http响应中定位汇率。请假设jquery已包含在withing <head></head>标记

{
    "Realtime Currency Exchange Rate": {
        "1. From_Currency Code": "XRP",
        "2. From_Currency Name": "Ripples",
        "3. To_Currency Code": "GBP",
        "4. To_Currency Name": "British Pound Sterling",
        "5. Exchange Rate": "1.07367766",
        "6. Last Refreshed": "2017-12-28 19:42:42",
        "7. Time Zone": "UTC"
    }
}

HTML

<select id="asset">
    <option value="">Please Select...</option>
    <option value="BTC">Bitcon ($BTC)</option>
    <option value="BCH">Bitcon Cash ($BTH)</option>
    <option value="ETH">Ethereum ($ETH)</option>
    <option value="LTC">Litecoin ($LTC)</option>
    <option value="XRP">Ripple ($XRP)</option>

</select>

<div id="output" class="hide">


</div>

JS

var output = $("#output");
output.removeClass("hide");
output.hide();
$("#asset").on('change', function() {
  var coin = $("#asset").val();

 $.ajax({
  type: "GET",
      url: "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=" + coin + "&to_currency=GBP&apikey=API_KEY_HERE",
      success: function(data) {
         output.html(JSON.stringify(data));

         // Would like to get the Exchange Rate only for use later on.
      }
  });

  output.slideDown(); 

});

2 个答案:

答案 0 :(得分:1)

尝试:

data["Realtime Currency Exchange Rate"]["5. Exchange Rate"]

let jsonData = {
  "Realtime Currency Exchange Rate": {
    "1. From_Currency Code": "XRP",
    "2. From_Currency Name": "Ripples",
    "3. To_Currency Code": "GBP",
    "4. To_Currency Name": "British Pound Sterling",
    "5. Exchange Rate": "1.07367766",
    "6. Last Refreshed": "2017-12-28 19:42:42",
    "7. Time Zone": "UTC"
  }
};

console.log( jsonData["Realtime Currency Exchange Rate"]["5. Exchange Rate"] );

答案 1 :(得分:0)

使用数据对象选择您需要的位,我刚刚在下面的示例中将其添加到警报中:

lol