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

标签 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”结果。

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

最佳答案

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;

等等。

关于javascript - 从 jQuery 或 JS 中的 json 对象中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10926965/

相关文章:

javascript - 单击将文本框更改为文本区域

javascript - 使用 Knockout.js 自定义验证规则

javascript - 如何在 D3.js 中添加箭头链接?

javascript - 从具有相似键的 JSON 对象中检索数据

javascript - 在悬停期间更改 Div 的边框

javascript - 如何在流中定义和导入类类型?

javascript - 1 个帖子中的多个 Facebook Live react 民意调查

javascript - JS 中如何将对象字符串转换为对象数组?

json - 使用JQ(YQ)添加/删除k8s入口 list 中的后端 block

javascript - 是否有 jQuery 修复程序可以使 CSS3 在所有浏览器中工作?