From 268daf853693d28efb4160ab6c1d72360f65a1a5 Mon Sep 17 00:00:00 2001 From: Sergey Potapov Date: Mon, 2 May 2016 14:37:13 +0200 Subject: [PATCH] Handle conditions within object child nodes --- lib/jsonpath/enumerable.rb | 12 ++++++++---- test/test_jsonpath.rb | 15 +++++++++++++-- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/lib/jsonpath/enumerable.rb b/lib/jsonpath/enumerable.rb index 373ac66..f35c239 100644 --- a/lib/jsonpath/enumerable.rb +++ b/lib/jsonpath/enumerable.rb @@ -31,13 +31,17 @@ def each(context = @object, key = nil, pos = 0, &blk) when ?? raise "Cannot use ?(...) unless eval is enabled" unless allow_eval? case node - when Hash, Array - (node.is_a?(Hash) ? node.keys : (0..node.size)).each do |e| - @_current_node = node[e] + when Array + node.size.times do |index| + @_current_node = node[index] if process_function_or_literal(sub_path[1, sub_path.size - 1]) each(@_current_node, nil, pos + 1, &blk) end end + when Hash + if process_function_or_literal(sub_path[1, sub_path.size - 1]) + each(@_current_node, nil, pos + 1, &blk) + end else yield node if process_function_or_literal(sub_path[1, sub_path.size - 1]) end @@ -54,7 +58,7 @@ def each(context = @object, key = nil, pos = 0, &blk) end_idx = (array_args[1] && process_function_or_literal(array_args[1], -1) || (sub_path.count(':') == 0 ? start_idx : -1)) next unless end_idx if start_idx == end_idx - next unless start_idx < node.size + next unless start_idx < node.size end end start_idx %= node.size diff --git a/test/test_jsonpath.rb b/test/test_jsonpath.rb index 76c267b..73f5728 100644 --- a/test/test_jsonpath.rb +++ b/test/test_jsonpath.rb @@ -155,7 +155,7 @@ def test_wildcard_empty_array assert_equal [], JsonPath.on(object, "$..bicycle.tire[*]") end - def test_support_filter_by_childnode_value + def test_support_filter_by_array_childnode_value assert_equal [@object['store']['book'][3]], JsonPath.new("$..book[?(@.price > 20)]").on(@object) end @@ -171,7 +171,18 @@ def test_support_filter_by_childnode_value_and_select_child_key def test_support_filter_by_childnode_value_over_childnode_and_select_child_key assert_equal ["Osennie Vizity"], JsonPath.new("$..book[?(@.written.year == 1996)].title").on(@object) end - + + def test_support_filter_by_object_childnode_value + data = { + "data" => { + "type" => "users", + "id" => "123" + } + } + assert_equal [{"type"=>"users", "id"=>"123"}], JsonPath.new("$.data[?(@.type == 'users')]").on(data) + assert_equal [] , JsonPath.new("$.data[?(@.type == 'admins')]").on(data) + end + def example_object { "store"=> { "book" => [