2011-10-28 135 views
2

我正在使用RestClient在Ruby中編寫一些測試。測試工作正常,響應是JSON,但是當我解析JSON並嘗試提取我正在尋找的值時,出現錯誤說明IndexError: key not found如何從JSON響應中提取值?

IMO,我的代碼應該工作。該JSON是:

{"user":{"@xmlns":{"dvi":"http:\/\/xxxx","a":"http:\/\/xxxx","$":"http:\/\/xxxx"},"link":[{"@rel":"self","$":"http:\/\/xxxx"},{"@rel":"user","$":"http:\/\/xxxx"},{"@rel":"usage","$":"xxxx"},{"@rel":"repositories","$":"http:\/\/xxxx"},{"@rel":"shares","$":"http:\/\/xxxx"},{"@rel":"shareMemberships","$":"http:\/\/xxxx"}],"phone":{"$":"3518"},"email":{"$":""},"firstName":{"$":"Jim"},"lastName":{"$":"Joe"},"uid":{"$":"91bc7a72bc724e5e9b53e688dd105ed4"},"accountName":{"$":"3518"},"notificationMethod":{"$":"email sms"},"accountStatus":{"$":"Active"},"serviceLevel":{"$":"5"},"repositoryCount":{"$":"1"},"usage":{"allowed":{"$":"5368709120"},"total":{"$":"1024"}},"contactEmail":{"$":"[email protected]"}}} 

,我的代碼是:

result = jsonabove 
jdoc = JSON.parse(result) 
notificationMethod = jdoc.fetch("notificationMethod") 

return notificationMethod 

回答

4

這是怎麼回事,因爲notificationMethod關鍵是不是在你的哈希的第一級密鑰。在準備JSON#parse方法之後,您只有一個名爲user的密鑰。您應該通過此密鑰獲取值,然後應用您的notificationMethod密鑰。它看起來像這樣:

require 'json' 

result = <<HERE 
{"user":{"......"}} 
HERE 

jdoc = JSON.parse(result) 
notificationMethod = jdoc.fetch("user").fetch("notificationMethod") 
puts notificationMethod 
+0

就是這樣!太感謝了! – Adrian

+0

一點都沒有,很高興幫助你! – WarHog