2012-06-07 31 views
7

我想使用https://raw.github.com/currencybot/open-exchange-rates/master/latest.json从jQuery的JSON对象或提取数据JS

提供作为一个初步的测试货币数据,我已经创造了这个简化版本作为嵌入对象:

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和过滤器函数,但我无法弄清楚如何隔离对象的'rates'部分,然后得到我想要的速度。

回答

18
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; 

等等。

+0

非常好,那正是我想要的。我不知道它会如此简单。 – Joseph

+0

我的JSON数据是“{”0“:{”level1“:”完成“,”level2“:”完成“,”level3“:”否“}}'如何将这个提取到每个变量中?我尝试使用'$ .each'方法,但返回未定义'var level1 = ele [0] .level1;' – 151291

5

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

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

它给了我“未定义”。请帮助 –