2011-10-28 134 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