使用jquery从json获取特定值

时间:2017-01-18 02:52:50

标签: jquery json

我试图从http://api.coindesk.com/v1/bpi/currentprice/usd.json获取一个类似于此内容的数据

{
    "time": {
        "updated": "Jan 18, 2017 02:55:00 UTC",
        "updatedISO": "2017-01-18T02:55:00+00:00",
        "updateduk": "Jan 18, 2017 at 02:55 GMT"
    },
    "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
    "bpi": {
        "USD": {
            "code": "USD",
            "rate": "888.9525",
            "description": "United States Dollar",
            "rate_float": 888.9525
        }
    }
}

我希望获得的数据仅为" bpi"。" USD"。" rate"部分但我无法这样做。

$.getJSON("demo_ajax_json.js", function(result){
    $.each(result, function(i, field){
        $("div").append(field + " ");
    });
});

我试图把它放在这里,但我因为堆叠问题而遇到了问题?"键和值。有人能指引我走向正确的方向吗?如果我理解正确,我有JSON.parse,但我仍然不完全理解它

2 个答案:

答案 0 :(得分:2)

当您从$.getJSON电话中获取有效的JavaScript对象时,您可以通过这种方式访问​​您想要的属性

data.bpi.USD.rate

检查以下代码段



$(document).ready(function() {
  $.getJSON('http://api.coindesk.com/v1/bpi/currentprice/usd.json')
    .success(getCurrentPriceCompleted)
    .error(getCurrentPriceFailed);

  function getCurrentPriceCompleted(data) {
    console.log(data.bpi.USD.rate);
  }

  function getCurrentPriceFailed(error) {
    console.log(error);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
  <legend>The JavaScript Object (response from server):</legend>
  <code>
  {
   "time":{
      "updated":"Jan 18, 2017 02:56:00 UTC",
      "updatedISO":"2017-01-18T02:56:00+00:00",
      "updateduk":"Jan 18, 2017 at 02:56 GMT"
   },
   "disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
   "bpi":{
      "USD":{
         "code":"USD",
         "rate":"888.7975",
         "description":"United States Dollar",
         "rate_float":888.7975
      }
   }
}
  </code>
</fieldset>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

&#13;
&#13;
var data = {
	"time": {
		"updated": "Jan 18, 2017 02:55:00 UTC",
		"updatedISO": "2017-01-18T02:55:00+00:00",
		"updateduk": "Jan 18, 2017 at 02:55 GMT"
	},
	"disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
	"bpi": {
		"USD": {
			"code": "USD",
			"rate": "888.9525",
			"description": "United States Dollar",
			"rate_float": 888.9525
		}
	}
};


console.log(data.bpi.USD.rate)
&#13;
&#13;
&#13;

像这样使用