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



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

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

如何获得参数'属性'和'方向'?

你可以这样做:

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将返回那个哈希值。在这一点上,它只是通常的方法来获得值。我使用values_at将它们作为数组返回。

传递JSON[]字符串和JSON将尝试解析它,期望JSON编码的对象。向JSON[]传递另一个对象,如数组或散列,JSON将其编码为其序列化格式。

最新更新