一尘不染

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

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
    }
}];

我想要做的就是以某种方式使用例如“ EUR”作为条件查询/ grep /过滤json对象,并使其返回一个名为“ rate”的变量,其结果为“
0.795767”。

我已经看过JQuery的grep和filter函数,但无法弄清楚如何仅隔离对象的“ rates”部分,然后获得所需的速率。


阅读 281

收藏
2020-07-27

共1个答案

一尘不染

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

演示

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

var rates = obj[0].rates;

现在,

rates.EUR;
rates.GBP;

等等。

2020-07-27