2012-06-07 30 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

它給了我「未定義」。請幫助 –