4

我在 config 中存储了一个哈希路径(使用 ruby​​ in JsonPath),在一种情况下,我需要为一个变量获取多个字段。

例子:

{
 "a" => 1,
 "b" => 2,
 "c" => 3,
 "d" => 4,
 "e" => 5,
}

对于一个变量,我需要值为3-4-5. 有没有办法一次性访问"c","d""e"from JsonPath

$$$$$$$$$$$$$编辑$$$$$$$$$$$$$$

这似乎是目前 jsonpath gem 的限制,请随时在其他 gem/方式上提出建议。

4

2 回答 2

2

Yes..do as below using Hash#values_at:

hsh = {
 "a" => 1,
 "b" => 2,
 "c" => 3,
 "d" => 4,
 "e" => 5,
}

hsh.values_at("c","d","e").join('-')
# => "3-4-5"
于 2014-01-01T12:51:30.307 回答
0

我通过编写一个小函数来解决此函数,该函数将参数作为逗号分隔路径的多个路径的数组并返回这些路径的值,以下是代码:-

def find_multiple_path hash, path
  return path.inject([]){|tmp,p| tmp<< JsonPath.on(hash, p)}.flatten.join("-") if path and path.kind_of?(Array)

  return path.split(",").inject([]){|tmp,p| tmp<< JsonPath.on(hash, p)}.flatten.join("-") if path and path.include?(",") and path.include?("$")
end

其中路径可以是 ["$.c","$.d","$.e"] 或 "$.c,$.d,$.e"。

于 2014-04-05T10:02:02.657 回答