如何从参数数组中检索Ruby/Sinatra参数?
我的ExtJS前端将这样一个参数散列发送到我的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
{"_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将把它编码成它的序列化格式