如何从JSON响应中提取值?

时间:2011-10-28 13:49:34

标签: ruby json

我正在使用RestClient在Ruby中编写一些测试。测试工作正常,响应是JSON,但是当我解析JSON并尝试提取我正在寻找的值时,我收到错误IndexError: key not found

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":{"$":"3518012343001"},"email":{"$":""},"firstName":{"$":"Jim"},"lastName":{"$":"Joe"},"uid":{"$":"91bc7a72bc724e5e9b53e688dd105ed4"},"accountName":{"$":"3518012343001"},"notificationMethod":{"$":"email sms"},"accountStatus":{"$":"Active"},"serviceLevel":{"$":"5"},"repositoryCount":{"$":"1"},"usage":{"allowed":{"$":"5368709120"},"total":{"$":"1024"}},"contactEmail":{"$":"jim@joe.com"}}}

我的代码是:

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

return notificationMethod

1 个答案:

答案 0 :(得分:4)

这种情况正在发生,因为notificationMethod键不是哈希中的第一级键。准备好JSON#parse方法后,您只有一个名为user的密钥。您应该通过此密钥获取值,然后应用notificationMethod密钥。它看起来像这样:

require 'json'

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

jdoc = JSON.parse(result)
notificationMethod = jdoc.fetch("user").fetch("notificationMethod")
puts notificationMethod
相关问题