从jQuery或JS中的json对象中提取数据

时间:2012-06-07 06:49:40

标签: javascript jquery json

我想使用https://raw.github.com/currencybot/open-exchange-rates/master/latest.json

提供的货币数据

作为初步测试,我已经将其作为内联对象创建了一个简化版本:

var obj = [
{
    "disclaimer": "This data is collected from various providers and provided free of charge for informational purposes only, with no guarantee whatsoever of accuracy, validity, availability, or fitness for any purpose; use at your own risk. Other than that, have fun! More info: http://openexchangerates.org/terms/",
    "license": "Data collected from various providers with public-facing APIs; copyright may apply; not for resale; no warranties given. Full license info: http://openexchangerates.org/license/",
    "timestamp": 1339036116,
    "base": "USD",
    "rates": {
        "EUR": 0.795767,
        "GBP": 0.645895,
        "JPY": 79.324997,
        "USD": 1
    }
}];

我希望能够以某种方式查询/ grep /过滤json对象,例如“EUR”作为标准,并让它返回一个名为'rate'的变量,其值为'0.795767'as结果。

我查看了JQuery grep和过滤器函数,但我无法弄清楚如何仅仅隔离对象的'rates'部分然后获得我想要的速率。

3 个答案:

答案 0 :(得分:19)

var obj = [
{
    "disclaimer": "This data is collected from various providers and provided free of charge for informational purposes only, with no guarantee whatsoever of accuracy, validity, availability, or fitness for any purpose; use at your own risk. Other than that, have fun! More info: http://openexchangerates.org/terms/",
    "license": "Data collected from various providers with public-facing APIs; copyright may apply; not for resale; no warranties given. Full license info: http://openexchangerates.org/license/",
    "timestamp": 1339036116,
    "base": "USD",
    "rates": {
        "EUR": 0.795767,
        "GBP": 0.645895,
        "JPY": 79.324997,
        "USD": 1
    }
}];

obj[0].rates.EUR; // output: 0.795767

obj[0].rates['EUR']; output: //0.795767

<强> DEMO

如果要在另一个变量中隔离速率并使用该变量,请尝试以下操作:

var rates = obj[0].rates;

现在,

rates.EUR;
rates.GBP;

等等。

答案 1 :(得分:5)

您还可以使用Javascript的JSON.parse()函数将JSON字符串转换为Javascript JSON对象。

var JSONObject = JSON.parse("{'value1' : 1, 'value2' : 2}");
console.log(JSONObject.value1);  // Prints '1'..

答案 2 :(得分:0)

数据包含FRELD6 尝试:

var reldte;
var sdata = JSON.parse(data);
 $(sdata).each(function () {
        reldte = RefineDate(this.FRELD6.toString());
}