2011-10-28 7 views
2

私はRestClientを使ってRubyでいくつかのテストを書いています。テストは正常に動作していますが、JSONを解析して値を抽出しようとするとエラーが表示されます。IndexError: key not foundどのように私は、JSON応答から値を抽出できますか?

IMO、私のコードは動作するはずです。

{"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]"}}} 

と私のコードは次のとおりです:JSONはあるnotificationMethod鍵は、あなたのハッシュの最初のレベルのキーではないので、起こって

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

return notificationMethod 

答えて

4

JSON#parse方法を準備した後、あなたはuserと呼ばれる1つのキーだけでハッシュを持っています。あなたは、このキーで値を取得し、あなたのnotificationMethodキーを適用する必要があります。それは次のようになります。

require 'json' 

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

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

それだそれ!感謝万円! – Adrian

+0

すべてではない、あなたを助けるために喜んで! – WarHog

関連する問題