从对象分配给变量

时间:2018-01-28 17:40:43

标签: javascript jquery

拥有以下JSON

[
  {
    "id": "bitcoin", 
    "name": "Bitcoin", 
    "symbol": "BTC", 
    "rank": "1", 
    "price_usd": "11735.0", 
    "price_btc": "1.0", 
    "24h_volume_usd": "8281180000.0", 
    "market_cap_usd": "197517206570", 
    "available_supply": "16831462.0", 
    "total_supply": "16831462.0", 
    "max_supply": "21000000.0", 
    "percent_change_1h": "0.07", 
    "percent_change_24h": "2.17", 
    "percent_change_7d": "0.21", 
    "last_updated": "1517160566"
  }
]

我需要使用"price_usd"$.getJSON()的值分配给某个变量。

这不起作用

$.getJSON("test.js",function (data) {
        var test = data.price_usd;  
}

2 个答案:

答案 0 :(得分:0)

您需要使用数组的索引,在本例中为

 var test = data[0].price_usd;

<强>样本

&#13;
&#13;
var data = [
{
    "id": "bitcoin", 
    "name": "Bitcoin", 
    "symbol": "BTC", 
    "rank": "1", 
    "price_usd": "11735.0", 
    "price_btc": "1.0", 
    "24h_volume_usd": "8281180000.0", 
    "market_cap_usd": "197517206570", 
    "available_supply": "16831462.0", 
    "total_supply": "16831462.0", 
    "max_supply": "21000000.0", 
    "percent_change_1h": "0.07", 
    "percent_change_24h": "2.17", 
    "percent_change_7d": "0.21", 
    "last_updated": "1517160566"
}
];
var test = data[0].price_usd; 
console.log(test);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

给定的JSON数据是对象的数组。所以要获得price_btc,你必须为它提供索引。 例如:

var priceBtc = data[0].price_btc