Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.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/Sinatra参数?_Ruby_Hashmap_Params - Fatal编程技术网

如何从参数数组中检索Ruby/Sinatra参数?

如何从参数数组中检索Ruby/Sinatra参数?,ruby,hashmap,params,Ruby,Hashmap,Params,我的ExtJS前端将这样一个参数散列发送到我的Sinatra后端: {"_dc"=>"1365959782607", "page"=>"6", "start"=>"250", "limit"=>"50", "sort"=>"[{\"property\":\"port\",\"direction\":\"ASC\"}]"} 如何获取参数“property”和“direction”?您可以通过以下方式进行操作: require 'json' a = {"_dc"=&g

我的ExtJS前端将这样一个参数散列发送到我的Sinatra后端:

{"_dc"=>"1365959782607", "page"=>"6", "start"=>"250", "limit"=>"50", "sort"=>"[{\"property\":\"port\",\"direction\":\"ASC\"}]"}

如何获取参数“property”和“direction”?

您可以通过以下方式进行操作:

require 'json'
a = {"_dc"=>"1365959782607", "page"=>"6", "start"=>"250", "limit"=>"50", "sort"=>"[{\"property\":\"port\",\"direction\":\"ASC\"}]"}

sort = JSON.parse a["sort"]
p sort[0]["property"] # "port"
p sort[0]["direction"]  # "ASC"

你的问题与Sinatra无关,它是如何从散列中提取值并处理JSON的基本问题:

require 'json'
hash = {"_dc"=>"1365959782607", "page"=>"6", "start"=>"250", "limit"=>"50", "sort"=>"[{\"property\":\"port\",\"direction\":\"ASC\"}]"}

JSON[hash['sort']].first.values_at('property', 'direction')
=> ["port", "ASC"]
使用
JSON[hash['sort']]
解析序列化对象将返回一个包含单个哈希的数组
first
将返回该散列。在这一点上,它只是获取值的常用方法。我使用处的
值\u将它们作为数组返回

传递
JSON[]
一个字符串,JSON将尝试解析它,需要一个JSON编码的对象。传递另一个对象,比如数组或散列,JSON将把它编码成它的序列化格式