I need to find a certain hash element where one of the keys is equal to a certain value. I've tried many ways and can't seem to figure it out with jsonpath
gem.
Need to get tire
tag where grip == 'bad'
require "jsonpath"
hash = {
:id => 1,
:cars => [
{:id => 1, :tire => {:grip => "good", :color => "black"}},
{:id => 2, :tire => {:grip => "bad", :color => "red"}},
{:id => 3, :tire => {:grip => "good", :color => "green"}}
]
}
puts JsonPath.on(hash, "$..tire[?(@['grip'] == 'bad')]").inspect
No results.
The [?()]
filter only works for arrays (or at least for either arrays or hashes, not both at the same time). In order for it to work, I had to enclose the :tire
hash in an array.
Original:
:tire => {:grip => "good", :color => "black"}
New:
:tire => [{:grip => "good", :color => "black"}]
That's a "fix" that works for me. It would be better if someone fixed the jsonpath
gem to make it work for both arrays and hashes (of the same type and at the same time).