Ruby 如何从JSON响应中提取值?
我正在使用RestClient用Ruby编写一些测试。测试工作正常,响应是JSON格式的,但是当我解析JSON并尝试提取我要查找的值时,会出现一个错误,显示为Ruby 如何从JSON响应中提取值?,ruby,json,Ruby,Json,我正在使用RestClient用Ruby编写一些测试。测试工作正常,响应是JSON格式的,但是当我解析JSON并尝试提取我要查找的值时,会出现一个错误,显示为indexer:key not found 依我看,我的代码应该有效。JSON是: {"user":{"@xmlns":{"dvi":"http:\/\/xxxx","a":"http:\/\/xxxx","$":"http:\/\/xxxx"},"link":[{"@rel":"self","$":"http:\/\/xxxx"},{"@
indexer:key not found
依我看,我的代码应该有效。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
这是因为
notificationMethod
键不是散列中的第一级键。在准备了JSON#parse
方法之后,您有一个只有一个键的散列,名为user
。您应该通过该键获取值,然后应用notificationMethod
键。看起来是这样的:
require 'json'
result = <<HERE
{"user":{"......"}}
HERE
jdoc = JSON.parse(result)
notificationMethod = jdoc.fetch("user").fetch("notificationMethod")
puts notificationMethod
require'json'
结果=一点也不,很高兴帮助你!