Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何从JSON响应中提取值?_Ruby_Json - Fatal编程技术网

Ruby 如何从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"},{"@

我正在使用RestClient用Ruby编写一些测试。测试工作正常,响应是JSON格式的,但是当我解析JSON并尝试提取我要查找的值时,会出现一个错误,显示为
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'

结果=一点也不,很高兴帮助你!